Skip to content

Build your personal knowledge base with Trilium Notes

test(core): improve coverage for core services

Elian Doran1269e75b65df
diff --git a/packages/trilium-core/src/services/bootstrap_utils.spec.ts b/packages/trilium-core/src/services/bootstrap_utils.spec.ts
new file mode 100644
index 0000000000..6431635cdd
--- /dev/null
+++ b/packages/trilium-core/src/services/bootstrap_utils.spec.ts
@@ -0,0 +1,118 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import attributes from "./attributes.js";
+import getSharedBootstrapItems, { getIconConfig } from "./bootstrap_utils.js";
+import * as cls from "./context.js";
+import notes from "./notes.js";
+import options from "./options.js";
+
+const ASSET_PATH = "assets-x";
+
+function withTheme<T>(theme: string, fn: () => T): T {
+ const previous = options.getOption("theme");
+ try {
+ cls.init(() => options.setOption("theme", theme));
+ return fn();
+ } finally {
+ cls.init(() => options.setOption("theme", previous));
+ }
+}
+
+/** Returns the bootstrap payload for an initialized DB, narrowed to the full shape. */
+function fullPayload(theme: string) {
+ const items = withTheme(theme, () => getSharedBootstrapItems(ASSET_PATH, true));
+ if (!("customThemeCssUrl" in items)) {
+ throw new Error("Expected the initialized bootstrap payload");
+ }
+ return items;
+}
+
+describe("bootstrap_utils (real DB)", () => {
+ afterEach(() => cls.reset());
+
+ it("returns the minimal setup payload before the DB is initialized", () => {
+ const items = getSharedBootstrapItems(ASSET_PATH, false);
+
+ expect(items.dbInitialized).toBe(false);
+ expect(items.theme).toBe("next");
+ expect(items.themeCssUrl).toBe(false);
+ expect(items.appCssNoteIds).toEqual([]);
+ // Common items + icon config are always present.
+ expect(items.assetPath).toBe(ASSET_PATH);
+ expect(items.iconRegistry).toBeTruthy();
+ expect(typeof items.iconPackCss).toBe("string");
+ });
+
+ it("returns the full payload once the DB is initialized, including app CSS note ids", () => {
+ const appCssNoteId = cls.init(() => {
+ const { note } = notes.createNewNote({
+ parentNoteId: "root",
+ title: "App CSS",
+ content: "body {}",
+ type: "code",
+ mime: "text/css"
+ });
+ attributes.createLabel(note.noteId, "appCss", "");
+ return note.noteId;
+ });
+
+ const items = fullPayload("next");
+
+ expect(items.dbInitialized).toBe(true);
+ expect(typeof items.maxEntityChangeIdAtLoad).toBe("number");
+ expect(typeof items.maxEntityChangeSyncIdAtLoad).toBe("number");
+ expect(items.isProtectedSessionAvailable).toBe(false);
+ expect(items.theme).toBe("next");
+ expect(items.appCssNoteIds).toContain(appCssNoteId);
+ });
+
+ it("maps each built-in theme to its stylesheet URL", () => {
+ const expectations: Record<string, string | false> = {
+ auto: `${ASSET_PATH}/stylesheets/theme.css`,
+ light: false,
+ dark: `${ASSET_PATH}/stylesheets/theme-dark.css`,
+ next: `${ASSET_PATH}/stylesheets/theme-next.css`,
+ "next-light": `${ASSET_PATH}/stylesheets/theme-next-light.css`,
+ "next-dark": `${ASSET_PATH}/stylesheets/theme-next-dark.css`
+ };
+
+ for (const [theme, expected] of Object.entries(expectations)) {
+ const items = fullPayload(theme);
+ expect(items.themeCssUrl, `theme=${theme}`).toBe(expected);
+ // Built-in themes never expose a custom CSS URL.
+ expect(items.customThemeCssUrl, `theme=${theme}`).toBeUndefined();
+ }
+ });
+
+ it("resolves a custom theme note to a download URL", () => {
+ const noteId = cls.init(() => {
+ const { note } = notes.createNewNote({
+ parentNoteId: "root",
+ title: "Custom Theme",
+ content: "body {}",
+ type: "code",
+ mime: "text/css"
+ });
+ attributes.createLabel(note.noteId, "appTheme", "myCustomTheme");
+ attributes.createLabel(note.noteId, "appThemeBase", "next-dark");
+ return note.noteId;
+ });
+
+ const items = fullPayload("myCustomTheme");
+ expect(items.themeCssUrl).toBe(`api/notes/download/${noteId}`);
+ expect(items.customThemeCssUrl).toBe(`api/notes/download/${noteId}`);
+ expect(items.themeBase).toBe("next-dark");
+ });
+
+ it("falls back to the baseline light theme for an unknown theme with no matching note", () => {
+ const items = fullPayload("ghostThemeWithoutNote");
+ expect(items.themeCssUrl).toBe(false);
+ expect(items.customThemeCssUrl).toBeUndefined();
+ });
+
+ it("getIconConfig produces an icon registry and CSS", () => {
+ const config = getIconConfig(ASSET_PATH);
+ expect(config.iconRegistry).toBeTruthy();
+ expect(typeof config.iconPackCss).toBe("string");
+ });
+});
diff --git a/packages/trilium-core/src/services/file_based_log.spec.ts b/packages/trilium-core/src/services/file_based_log.spec.ts
new file mode 100644
index 0000000000..43b774bbb7
--- /dev/null
+++ b/packages/trilium-core/src/services/file_based_log.spec.ts
@@ -0,0 +1,190 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import * as cls from "./context.js";
+import FileBasedLogService, { type LogFileInfo } from "./file_based_log.js";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * In-memory concrete implementation used to exercise the shared logic of the
+ * abstract {@link FileBasedLogService}. All side effects are captured in plain
+ * fields so the test can assert on them. Public `call*` wrappers expose the
+ * protected helpers for direct unit testing.
+ */
+class MemoryLogService extends FileBasedLogService {
+ eolValue = "\n";
+ retentionDays = 7;
+ dirEnsured = false;
+ files: Record<string, string[]> = {};
+ currentFile = "";
+ deleted: string[] = [];
+ failingDeletes = new Set<string>();
+ fileList: LogFileInfo[] = [];
+ listShouldThrow = false;
+
+ protected get eol(): string {
+ return this.eolValue;
+ }
+ protected override ensureLogDirectory(): void {
+ this.dirEnsured = true;
+ }
+ protected override openLogFile(fileName: string): void {
+ this.currentFile = fileName;
+ this.files[fileName] ??= [];
+ }
+ protected override closeLogFile(): void {}
+ protected override writeEntry(entry: string): void {
+ this.files[this.currentFile].push(entry);
+ }
+ protected override readLogFile(fileName: string): string | null {
+ return this.files[fileName]?.join("") ?? null;
+ }
+ protected override async listLogFiles(): Promise<LogFileInfo[]> {
+ if (this.listShouldThrow) throw new Error("list failed");
+ return this.fileList;
+ }
+ protected override async deleteLogFile(name: string): Promise<void> {
+ if (this.failingDeletes.has(name)) throw new Error(`cannot delete ${name}`);
+ this.deleted.push(name);
+ }
+ protected override getRetentionDays(): number {
+ return this.retentionDays;
+ }
+
+ // Wrappers exposing protected helpers for direct coverage.
+ callRotate() {
+ return this.rotateLogFile();
+ }
+ callCleanup() {
+ return this.cleanupOldLogFiles();
+ }
+ callCheckDateAndRotate(ms: number) {
+ return this.checkDateAndRotate(ms);
+ }
+ callGetScriptContext() {
+ return this.getScriptContext();
+ }
+ callFormatTime(ms: number) {
+ return this.formatTime(ms);
+ }
+}
+
+describe("FileBasedLogService (shared logic)", () => {
+ let log: MemoryLogService;
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ log = new MemoryLogService();
+ consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("initialize() sets up the directory and current log file, and is idempotent", async () => {
+ await log.initialize();
+ expect(log.dirEnsured).toBe(true);
+ expect(log.currentFile).toMatch(/^trilium-\d{4}-\d{2}-\d{2}\.log$/);
+
+ // Second call short-circuits.
+ log.dirEnsured = false;
+ await log.initialize();
+ expect(log.dirEnsured).toBe(false);
+ });
+
+ it("log()/info() write a timestamped entry and echo to the console", async () => {
+ await log.initialize();
+ log.log("hello world");
+ log.info("second");
+
+ const contents = log.getLogContents() ?? "";
+ expect(contents).toContain("hello world");
+ expect(contents).toContain("second");
+ // "HH:MM:SS.mmm message" format.
+ expect(contents).toMatch(/\d{2}:\d{2}:\d{2}\.\d{3} hello world/);
+ expect(consoleLogSpy).toHaveBeenCalledWith("hello world");
+ });
+
+ it("prefixes the entry with the script bundle id when one is in context", async () => {
+ await log.initialize();
+ cls.init(() => {
+ cls.set("bundleNoteId", "scriptXyz");
+ log.log("inside script");
+ });
+ expect(log.getLogContents() ?? "").toContain("[Script scriptXyz] inside script");
+ });
+
+ it("error() stringifies Error stacks and plain values", async () => {
+ await log.initialize();
+ log.error(new Error("boom"));
+ log.error("plain failure");
+
+ const contents = log.getLogContents() ?? "";
+ expect(contents).toContain("ERROR: ");
+ expect(contents).toContain("boom");
+ expect(contents).toContain("plain failure");
+ });
+
+ it("getScriptContext returns undefined when the context lookup throws", () => {
+ vi.spyOn(cls, "getContext").mockImplementation(() => {
+ throw new Error("no context");
+ });
+ expect(log.callGetScriptContext()).toBeUndefined();
+ });
+
+ it("checkDateAndRotate rotates and subtracts a day only past midnight rollover", () => {
+ expect(log.callCheckDateAndRotate(1000)).toBe(1000);
+ const overflowed = log.callCheckDateAndRotate(DAY_MS + 5000);
+ expect(overflowed).toBe(5000);
+ });
+
+ it("rotateLogFile opens a fresh file for the new day", async () => {
+ await log.initialize();
+ const before = log.currentFile;
+ await log.callRotate();
+ expect(log.currentFile).toBe(before); // same calendar day -> same name
+ expect(log.files[before]).toBeDefined();
+ });
+
+ it("formatTime pads hours and the three millisecond magnitudes", () => {
+ expect(log.callFormatTime(5)).toMatch(/00:00:00\.005$/);
+ expect(log.callFormatTime(50)).toMatch(/00:00:00\.050$/);
+ expect(log.callFormatTime(500)).toMatch(/00:00:00\.500$/);
+ expect(log.callFormatTime(11 * 60 * 60 * 1000)).toMatch(/^11:00:00/);
+ });
+
+ describe("cleanupOldLogFiles", () => {
+ const oldDate = () => new Date(Date.now() - 30 * DAY_MS);
+
+ it("keeps everything when retention is -1", async () => {
+ log.retentionDays = -1;
+ log.fileList = Array.from({ length: 10 }, (_, i) => ({ name: `f${i}.log`, mtime: oldDate() }));
+ await log.callCleanup();
+ expect(log.deleted).toEqual([]);
+ });
+
+ it("does nothing when there are at most the minimum number of files", async () => {
+ log.fileList = Array.from({ length: 5 }, (_, i) => ({ name: `f${i}.log`, mtime: oldDate() }));
+ await log.callCleanup();
+ expect(log.deleted).toEqual([]);
+ });
+
+ it("deletes the oldest files beyond the minimum when they exceed retention (retention 0 -> default)", async () => {
+ log.retentionDays = 0; // falls back to the default of 7 days
+ log.fileList = Array.from({ length: 10 }, (_, i) => ({ name: `old${i}.log`, mtime: oldDate() }));
+ log.failingDeletes.add("old1.log"); // one delete failure is swallowed
+ await log.callCleanup();
+ // 10 files - 7 kept = 3 candidates (old0..old2); old1 fails, so 2 deleted.
+ expect(log.deleted).toEqual(["old0.log", "old2.log"]);
+ });
+
+ it("does not delete recent files even beyond the minimum", async () => {
+ log.fileList = Array.from({ length: 10 }, (_, i) => ({ name: `recent${i}.log`, mtime: new Date() }));
+ await log.callCleanup();
+ expect(log.deleted).toEqual([]);
+ });
+
+ it("swallows errors from listing log files", async () => {
+ log.listShouldThrow = true;
+ await expect(log.callCleanup()).resolves.toBeUndefined();
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/i18n.spec.ts b/packages/trilium-core/src/services/i18n.spec.ts
new file mode 100644
index 0000000000..eecaed2be2
--- /dev/null
+++ b/packages/trilium-core/src/services/i18n.spec.ts
@@ -0,0 +1,56 @@
+import { dayjs, LOCALES } from "@triliumnext/commons";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import * as cls from "./context.js";
+import hidden_subtree from "./hidden_subtree.js";
+import { changeLanguage, getCurrentLocale, initTranslations, ordinal } from "./i18n.js";
+import options from "./options.js";
+import sql_init from "./sql_init.js";
+
+describe("i18n service (core)", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("ordinal formats a date with its ordinal day", () => {
+ expect(typeof ordinal(dayjs("2024-03-21"))).toBe("string");
+ });
+
+ it("changeLanguage switches i18next and restores the hidden subtree names", async () => {
+ const checkSpy = vi.spyOn(hidden_subtree, "checkHiddenSubtree").mockImplementation(() => {});
+
+ await changeLanguage("en");
+
+ expect(checkSpy).toHaveBeenCalledWith(true, { restoreNames: true });
+ });
+
+ it("getCurrentLocale resolves the option, falling back to English", () => {
+ const valid = getCurrentLocale();
+ expect(valid.id).toBeTruthy();
+ expect(LOCALES).toContainEqual(valid);
+
+ // Unknown locale id -> English fallback.
+ const previous = options.getOption("locale");
+ try {
+ cls.init(() => options.setOption("locale", "zz-nonexistent"));
+ expect(getCurrentLocale().id).toBe("en");
+ } finally {
+ cls.init(() => options.setOption("locale", previous));
+ }
+ });
+
+ it("getCurrentLocale returns English when the DB is not initialized", () => {
+ vi.spyOn(sql_init, "isDbInitialized").mockReturnValue(false);
+ expect(getCurrentLocale().id).toBe("en");
+ });
+
+ it("initTranslations logs a fallback when the locale option is empty", async () => {
+ const infoSpy = vi.spyOn(console, "info").mockImplementation(() => {});
+ const previous = options.getOption("locale");
+ try {
+ cls.init(() => options.setOption("locale", ""));
+ await initTranslations(async () => {});
+ expect(infoSpy).toHaveBeenCalled();
+ } finally {
+ cls.init(() => options.setOption("locale", previous));
+ }
+ });
+});
diff --git a/packages/trilium-core/src/services/image_provider.spec.ts b/packages/trilium-core/src/services/image_provider.spec.ts
new file mode 100644
index 0000000000..6d57dec942
--- /dev/null
+++ b/packages/trilium-core/src/services/image_provider.spec.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { ImageProvider, ProcessedImage } from "./image_provider.js";
+
+describe("image provider (core)", () => {
+ // The core bootstrap installs a real image provider, so to exercise the
+ // uninitialized guard we load a pristine copy of the module via resetModules.
+ it("throws before initialization and returns the installed provider afterwards", async () => {
+ vi.resetModules();
+ const mod = await import("./image_provider.js");
+
+ expect(() => mod.getImageProvider()).toThrow(/not initialized/);
+
+ const fake: ImageProvider = {
+ getImageType: vi.fn(() => ({ ext: "png", mime: "image/png" })),
+ processImage: vi.fn(async (): Promise<ProcessedImage> => ({
+ buffer: new Uint8Array(),
+ format: { ext: "png", mime: "image/png" }
+ }))
+ };
+ mod.initImageProvider(fake);
+ expect(mod.getImageProvider()).toBe(fake);
+ });
+});
diff --git a/packages/trilium-core/src/services/keyboard_actions.spec.ts b/packages/trilium-core/src/services/keyboard_actions.spec.ts
new file mode 100644
index 0000000000..ce8b3bdc69
--- /dev/null
+++ b/packages/trilium-core/src/services/keyboard_actions.spec.ts
@@ -0,0 +1,62 @@
+import type { OptionNames } from "@triliumnext/commons";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// `t` is imported as a named ESM export by keyboard_actions, which cannot be
+// spied directly. Mock i18next so we can force a "translations not loaded yet"
+// state on demand while delegating to the real implementation otherwise.
+const translationState = vi.hoisted(() => ({ broken: false }));
+vi.mock("i18next", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("i18next")>();
+ return {
+ ...actual,
+ t: (...args: unknown[]) => (translationState.broken ? "" : (actual.t as unknown as (...a: unknown[]) => unknown)(...args))
+ };
+});
+
+import * as cls from "./context.js";
+import keyboardActions from "./keyboard_actions.js";
+import options from "./options.js";
+
+function upsertOption(name: string, value: string) {
+ cls.init(() => {
+ if (options.getOptionOrNull(name as OptionNames) !== null) {
+ options.setOption(name as OptionNames, value);
+ } else {
+ options.createOption(name as OptionNames, value, false);
+ }
+ });
+}
+
+describe("keyboard_actions service", () => {
+ afterEach(() => {
+ translationState.broken = false;
+ vi.restoreAllMocks();
+ });
+
+ it("getDefaultKeyboardActions returns the action definitions", () => {
+ const actions = keyboardActions.getDefaultKeyboardActions();
+ expect(Array.isArray(actions)).toBe(true);
+ expect(actions.some((a) => "actionName" in a && a.actionName === "jumpToNote")).toBe(true);
+ });
+
+ it("throws if loaded before translations are available", async () => {
+ // keyboard_actions was already evaluated during the bootstrap (binding the
+ // real i18next), so re-import a fresh copy that picks up the mocked module.
+ vi.resetModules();
+ translationState.broken = true;
+ const freshModule = (await import("./keyboard_actions.js")).default;
+ expect(() => freshModule.getDefaultKeyboardActions()).toThrow(/before translations/);
+ });
+
+ it("getKeyboardActions overlays stored shortcuts and handles bad / unknown options", () => {
+ // A real action with an invalid JSON value -> parse error is logged, not thrown.
+ upsertOption("keyboardShortcutsJumpToNote", "not-json");
+ // An option referencing a non-existent action -> logged and skipped.
+ upsertOption("keyboardShortcutsNoSuchAction", "[]");
+
+ const actions = keyboardActions.getKeyboardActions();
+ expect(Array.isArray(actions)).toBe(true);
+ // The action is still present despite the unparseable override.
+ expect(actions.some((a) => "actionName" in a && a.actionName === "jumpToNote")).toBe(true);
+ });
+});
diff --git a/packages/trilium-core/src/services/keyboard_actions.ts b/packages/trilium-core/src/services/keyboard_actions.ts
index efcdf93c65..d90d281f22 100644
--- a/packages/trilium-core/src/services/keyboard_actions.ts
+++ b/packages/trilium-core/src/services/keyboard_actions.ts
@@ -866,6 +866,7 @@ function getKeyboardActions() {
for (const action of actions) {
if ("effectiveShortcuts" in action && action.effectiveShortcuts) {
+ /* v8 ignore next -- no default action pre-defines effectiveShortcuts; defensive seeding */
action.effectiveShortcuts = action.defaultShortcuts ? action.defaultShortcuts.slice() : [];
}
}
diff --git a/packages/trilium-core/src/services/log.spec.ts b/packages/trilium-core/src/services/log.spec.ts
new file mode 100644
index 0000000000..509b9b8f4b
--- /dev/null
+++ b/packages/trilium-core/src/services/log.spec.ts
@@ -0,0 +1,71 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import LogService from "./log.js";
+
+describe("LogService (base)", () => {
+ // The server/standalone hosts override LogService with file-based loggers, so
+ // the base implementation is never exercised by the bootstrap. Instantiate it
+ // directly and assert it forwards to the console.
+ afterEach(() => vi.restoreAllMocks());
+
+ it("forwards log/info/error to the console", () => {
+ const service = new LogService();
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ const infoSpy = vi.spyOn(console, "info").mockImplementation(() => {});
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ service.log("hello");
+ service.info("info-msg");
+ service.error("boom");
+
+ expect(logSpy).toHaveBeenCalledWith("hello");
+ expect(infoSpy).toHaveBeenCalledWith("info-msg");
+ expect(errorSpy).toHaveBeenCalledWith("ERROR: ", "boom");
+ });
+
+ it("getLogContents returns null and request() is a no-op by default", () => {
+ const service = new LogService();
+ expect(service.getLogContents()).toBeNull();
+ // Should not throw.
+ service.request({ url: "/x", method: "GET" }, { statusCode: 200 }, 5, 123);
+ });
+
+ it("banner ignores empty messages but renders a box for content (incl. word wrapping)", () => {
+ const service = new LogService();
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+
+ service.banner(undefined);
+ expect(logSpy).not.toHaveBeenCalled();
+
+ // Single short word: exercises the no-wrap path.
+ service.banner("ready");
+ expect(logSpy).toHaveBeenCalledOnce();
+ const shortBox = logSpy.mock.calls[0][0] as string;
+ expect(shortBox).toContain("ready");
+ expect(shortBox).toContain("╔");
+ expect(shortBox).toContain("╝");
+
+ logSpy.mockClear();
+
+ // A leading word longer than the terminal width forces the wrap branches:
+ // an oversized first word (empty `current`) followed by more words that
+ // overflow and flush the accumulated line.
+ const longWord = "x".repeat(120);
+ service.banner(`${longWord} some additional words that will wrap onto another line here`);
+ const wrappedBox = logSpy.mock.calls[0][0] as string;
+ expect(wrappedBox).toContain(longWord);
+ expect(wrappedBox.split("\n").length).toBeGreaterThan(4);
+ });
+});
+
+describe("log module singleton", () => {
+ it("getLog throws before init and initLog() falls back to a default LogService", async () => {
+ vi.resetModules();
+ const mod = await import("./log.js");
+
+ expect(() => mod.getLog()).toThrow(/not initialized/);
+
+ mod.initLog();
+ expect(mod.getLog()).toBeInstanceOf(mod.default);
+ });
+});
diff --git a/packages/trilium-core/src/services/messaging/index.spec.ts b/packages/trilium-core/src/services/messaging/index.spec.ts
new file mode 100644
index 0000000000..0d6ef2b9ad
--- /dev/null
+++ b/packages/trilium-core/src/services/messaging/index.spec.ts
@@ -0,0 +1,49 @@
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ getMessagingProvider,
+ initMessaging,
+ isMessagingInitialized,
+ sendMessageToAllClients
+} from "./index.js";
+import type { ClientMessageHandler, MessagingProvider } from "./types.js";
+
+function buildFakeProvider(): MessagingProvider & { sent: WebSocketMessage[] } {
+ const sent: WebSocketMessage[] = [];
+ return {
+ sent,
+ sendMessageToAllClients: vi.fn((message: WebSocketMessage) => sent.push(message)),
+ sendMessageToClient: vi.fn(() => true),
+ setClientMessageHandler: vi.fn((_handler: ClientMessageHandler) => {})
+ };
+}
+
+describe("messaging provider (core)", () => {
+ // The core test bootstrap (initializeCore) intentionally does not register a
+ // messaging provider, so these tests start from the uninitialized state and
+ // then install a fake. Each spec file runs in its own fork, so the mutation
+ // of the module singleton does not leak to other files.
+ it("reports uninitialized state, throws on get, and no-ops sends until a provider is set", () => {
+ expect(isMessagingInitialized()).toBe(false);
+ expect(() => getMessagingProvider()).toThrow(/not initialized/);
+
+ // Without a provider, sends are silently dropped (just a debug log).
+ const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => {});
+ sendMessageToAllClients({ type: "ping" });
+ expect(debugSpy).toHaveBeenCalledOnce();
+ debugSpy.mockRestore();
+ });
+
+ it("routes messages through the provider once initialized", () => {
+ const fake = buildFakeProvider();
+ initMessaging(fake);
+
+ expect(isMessagingInitialized()).toBe(true);
+ expect(getMessagingProvider()).toBe(fake);
+
+ sendMessageToAllClients({ type: "ping" });
+ expect(fake.sendMessageToAllClients).toHaveBeenCalledWith({ type: "ping" });
+ expect(fake.sent).toEqual([{ type: "ping" }]);
+ });
+});
diff --git a/packages/trilium-core/src/services/request.spec.ts b/packages/trilium-core/src/services/request.spec.ts
new file mode 100644
index 0000000000..f95b346647
--- /dev/null
+++ b/packages/trilium-core/src/services/request.spec.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from "vitest";
+
+import requestService, {
+ type ExecOpts,
+ getRequestProvider,
+ initRequest,
+ isRequestInitialized,
+ type RequestProvider
+} from "./request.js";
+
+describe("request provider (core)", () => {
+ // The core test bootstrap does not register a request provider, so the module
+ // starts uninitialized. Fork-per-file isolation keeps the mutation local.
+ it("throws and reports uninitialized until a provider is installed", () => {
+ expect(isRequestInitialized()).toBe(false);
+ expect(() => getRequestProvider()).toThrow(/not initialized/);
+ });
+
+ it("delegates exec/getImage to the installed provider", async () => {
+ const image = new ArrayBuffer(8);
+ const execMock = vi.fn(async (_opts: ExecOpts) => ({ ok: true }));
+ const fake: RequestProvider = {
+ exec: execMock as unknown as RequestProvider["exec"],
+ getImage: vi.fn(async () => image)
+ };
+
+ initRequest(fake);
+ expect(isRequestInitialized()).toBe(true);
+ expect(getRequestProvider()).toBe(fake);
+
+ const opts: ExecOpts = { proxy: null, method: "GET", url: "http://localhost/x", timeout: 1000 };
+ await expect(requestService.exec(opts)).resolves.toEqual({ ok: true });
+ expect(execMock).toHaveBeenCalledWith(opts);
+
+ await expect(requestService.getImage("http://localhost/img.png")).resolves.toBe(image);
+ expect(fake.getImage).toHaveBeenCalledWith("http://localhost/img.png");
+ });
+});
diff --git a/packages/trilium-core/src/services/setup.spec.ts b/packages/trilium-core/src/services/setup.spec.ts
new file mode 100644
index 0000000000..7ada44c6ca
--- /dev/null
+++ b/packages/trilium-core/src/services/setup.spec.ts
@@ -0,0 +1,124 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import appInfo from "./app_info.js";
+import * as cls from "./context.js";
+import options from "./options.js";
+import { type ExecOpts, initRequest, type RequestProvider } from "./request.js";
+import setupService from "./setup.js";
+import sqlInit from "./sql_init.js";
+import syncService from "./sync.js";
+
+let execImpl: (opts: ExecOpts) => Promise<unknown> = async () => ({});
+const fakeRequest: RequestProvider = {
+ exec: <T>(opts: ExecOpts) => execImpl(opts) as Promise<T>,
+ getImage: async () => new ArrayBuffer(0)
+};
+initRequest(fakeRequest);
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe("setup service", () => {
+ afterEach(() => {
+ execImpl = async () => ({});
+ vi.restoreAllMocks();
+ });
+
+ it("getSyncSeedOptions returns the document id and secret options", () => {
+ const seed = setupService.getSyncSeedOptions();
+ expect(seed).toHaveLength(2);
+ expect(seed[0]?.name).toBe("documentId");
+ expect(seed[1]?.name).toBe("documentSecret");
+ });
+
+ describe("hasSyncServerSchemaAndSeed", () => {
+ it("returns the schemaExists flag when sync versions match", async () => {
+ execImpl = async () => ({ syncVersion: appInfo.syncVersion, schemaExists: true });
+ await expect(setupService.hasSyncServerSchemaAndSeed()).resolves.toBe(true);
+
+ execImpl = async () => ({ syncVersion: appInfo.syncVersion, schemaExists: false });
+ await expect(setupService.hasSyncServerSchemaAndSeed()).resolves.toBe(false);
+ });
+
+ it("throws when the remote sync version differs", async () => {
+ execImpl = async () => ({ syncVersion: appInfo.syncVersion + 1, schemaExists: true });
+ await expect(setupService.hasSyncServerSchemaAndSeed()).rejects.toThrow(/sync protocol version/);
+ });
+ });
+
+ it("sendSeedToSyncServer posts the seed and resets the sync counters", async () => {
+ const requestedUrls: string[] = [];
+ execImpl = async (opts) => {
+ requestedUrls.push(opts.url);
+ return undefined;
+ };
+
+ // setOption (resetting the counters) needs an active CLS context, which the
+ // setup route would normally provide.
+ await cls.init(() => setupService.sendSeedToSyncServer());
+
+ expect(requestedUrls.some((u) => u.endsWith("/api/setup/sync-seed"))).toBe(true);
+ expect(Number(options.getOption("lastSyncedPush"))).toBe(0);
+ expect(Number(options.getOption("lastSyncedPull"))).toBe(0);
+ });
+
+ describe("setupSyncFromSyncServer", () => {
+ it("refuses when the local DB is already initialized", async () => {
+ const result = await setupService.setupSyncFromSyncServer("http://srv", "", "pw");
+ expect(result).toEqual({ result: "failure", error: "DB is already initialized." });
+ });
+
+ it("creates the database and triggers sync on success", async () => {
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
+ const createSpy = vi.spyOn(sqlInit, "createDatabaseForSync").mockResolvedValue(undefined as never);
+ vi.spyOn(sqlInit, "setDbAsInitialized").mockImplementation(() => {});
+ vi.spyOn(syncService, "sync").mockResolvedValue({ success: true });
+ execImpl = async () => ({ syncVersion: appInfo.syncVersion, options: [{ name: "documentId", value: "d" }] });
+
+ const result = await setupService.setupSyncFromSyncServer("http://srv", "proxy", "pw");
+
+ expect(result).toEqual({ result: "success" });
+ expect(createSpy).toHaveBeenCalledWith([{ name: "documentId", value: "d" }], "http://srv", "proxy");
+ });
+
+ it("fails on a sync version mismatch", async () => {
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
+ execImpl = async () => ({ syncVersion: appInfo.syncVersion + 5, options: [] });
+
+ const result = await setupService.setupSyncFromSyncServer("http://srv", "", "pw");
+ if (result.result !== "failure") throw new Error("expected a failure result");
+ expect(result.error).toMatch(/sync protocol version/);
+ });
+
+ it("fails gracefully when the seed request throws", async () => {
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
+ execImpl = async () => {
+ throw new Error("network down");
+ };
+
+ const result = await setupService.setupSyncFromSyncServer("http://srv", "", "pw");
+ expect(result).toEqual({ result: "failure", error: "network down" });
+ });
+ });
+
+ describe("triggerSync", () => {
+ it("marks the DB as initialized once a successful sync completes", async () => {
+ vi.spyOn(syncService, "sync").mockResolvedValue({ success: true });
+ const initializedSpy = vi.spyOn(sqlInit, "setDbAsInitialized").mockImplementation(() => {});
+
+ setupService.triggerSync();
+ await flush();
+
+ expect(initializedSpy).toHaveBeenCalled();
+ });
+
+ it("does not mark the DB initialized when sync fails", async () => {
+ vi.spyOn(syncService, "sync").mockResolvedValue({ success: false });
+ const initializedSpy = vi.spyOn(sqlInit, "setDbAsInitialized").mockImplementation(() => {});
+
+ setupService.triggerSync();
+ await flush();
+
+ expect(initializedSpy).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.ts
new file mode 100644
index 0000000000..f48b8e532a
--- /dev/null
+++ b/packages/trilium-core/src/services/sync.spec.ts
@@ -0,0 +1,306 @@
+import type { EntityChange } from "@triliumnext/commons";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import entityConstructor from "../becca/entity_constructor.js";
+import consistencyChecks from "./consistency_checks.js";
+import contentHashService from "./content_hash.js";
+import * as cls from "./context.js";
+import entityChangesService from "./entity_changes.js";
+import getInstanceId from "./instance_id.js";
+import options from "./options.js";
+import { type ExecOpts, initRequest, type RequestProvider } from "./request.js";
+import { getSql } from "./sql/index.js";
+import setupService from "./setup.js";
+import syncService from "./sync.js";
+import syncOptions from "./sync_options.js";
+import dateUtils from "./utils/date.js";
+
+interface ChangesResponse {
+ entityChanges: unknown[];
+ lastEntityChangeId: number;
+ outstandingPullCount: number;
+}
+interface CheckResponse {
+ maxEntityChangeId: number;
+ entityHashes: Record<string, Record<string, string>>;
+}
+
+interface FakeConfig {
+ login?: { instanceId: string; maxEntityChangeId: number } | null;
+ loginThrows?: Error;
+ changed?: ChangesResponse[];
+ check?: CheckResponse[];
+ onCheck?: (callIndex: number) => void;
+}
+
+let config: FakeConfig = {};
+let changedIdx = 0;
+let checkIdx = 0;
+const requestLog: Array<{ method: string; url: string }> = [];
+
+const fakeRequest: RequestProvider = {
+ exec: (<T>(opts: ExecOpts): Promise<T> => {
+ requestLog.push({ method: opts.method, url: opts.url });
+ const url = opts.url;
+ const reply = (value: unknown) => Promise.resolve(value as T);
+
+ if (url.includes("/api/login/sync")) {
+ if (config.loginThrows) return Promise.reject(config.loginThrows);
+ if (config.login === null) return reply(undefined);
+ return reply(config.login ?? { instanceId: "REMOTE_INSTANCE", maxEntityChangeId: 0 });
+ }
+ if (url.includes("/api/sync/changed")) {
+ const seq = config.changed ?? [{ entityChanges: [], lastEntityChangeId: 0, outstandingPullCount: 0 }];
+ return reply(seq[Math.min(changedIdx++, seq.length - 1)]);
+ }
+ if (url.includes("/api/sync/check-entity-changes")) return reply({});
+ if (url.includes("/api/sync/queue-sector")) return reply({});
+ if (url.includes("/api/sync/check")) {
+ config.onCheck?.(checkIdx);
+ const seq = config.check ?? [{ maxEntityChangeId: 0, entityHashes: {} }];
+ return reply(seq[Math.min(checkIdx++, seq.length - 1)]);
+ }
+ // /api/sync/update, /api/sync/finished, /api/setup/*
+ return reply({});
+ }) as RequestProvider["exec"],
+ getImage: async () => new ArrayBuffer(0)
+};
+initRequest(fakeRequest);
+
+const runSync = () => cls.init(() => syncService.sync());
+
+describe("sync service", () => {
+ beforeEach(() => {
+ config = {};
+ changedIdx = 0;
+ checkIdx = 0;
+ requestLog.length = 0;
+ vi.spyOn(syncOptions, "isSyncSetup").mockReturnValue(true);
+ vi.spyOn(syncOptions, "getSyncServerHost").mockReturnValue("http://sync.local");
+ vi.spyOn(syncOptions, "getSyncProxy").mockReturnValue("");
+ vi.spyOn(syncOptions, "getSyncTimeout").mockReturnValue(2000);
+ vi.spyOn(setupService, "hasSyncServerSchemaAndSeed").mockResolvedValue(true);
+ // Default: content hashes converge so the do/while loop terminates. Tests
+ // that want a divergence override this.
+ vi.spyOn(contentHashService, "checkContentHashes").mockReturnValue([]);
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("reports NOT_CONFIGURED when sync is not set up", async () => {
+ vi.spyOn(syncOptions, "isSyncSetup").mockReturnValue(false);
+ await expect(runSync()).resolves.toMatchObject({ success: false, errorCode: "NOT_CONFIGURED" });
+ });
+
+ it("runs a full login/push/pull/finish/check cycle successfully", async () => {
+ // Pull one (safe) change then drain; content check converges immediately.
+ config.changed = [
+ { entityChanges: [pulledOptionChange()], lastEntityChangeId: 9, outstandingPullCount: 1 },
+ { entityChanges: [], lastEntityChangeId: 9, outstandingPullCount: 0 }
+ ];
+ // Starts cleared: the pull marks it incomplete, convergence clears it again.
+ cls.init(() => options.setOption("syncIncomplete", "false"));
+
+ const result = await runSync();
+
+ expect(result).toEqual({ success: true });
+ // The incomplete marker is cleared on convergence.
+ expect(options.getOption("syncIncomplete")).toBe("false");
+ // The expected endpoints were exercised.
+ const urls = requestLog.map((r) => r.url);
+ expect(urls.some((u) => u.includes("/api/login/sync"))).toBe(true);
+ expect(urls.some((u) => u.includes("/api/sync/changed"))).toBe(true);
+ expect(urls.some((u) => u.includes("/api/sync/finished"))).toBe(true);
+ expect(urls.some((u) => u.includes("/api/sync/check"))).toBe(true);
+ });
+
+ it("re-runs the content check while the server reports outstanding pulls", async () => {
+ config.check = [
+ { maxEntityChangeId: 999_999_999, entityHashes: {} }, // lastSyncedPull < max -> loop again
+ { maxEntityChangeId: 0, entityHashes: {} } // converged
+ ];
+ await expect(runSync()).resolves.toEqual({ success: true });
+ });
+
+ it("re-queues failed sectors when content hashes diverge", async () => {
+ // First content check diverges (one failed sector), the next converges.
+ vi.mocked(contentHashService.checkContentHashes).mockReturnValueOnce([{ entityName: "notes", sector: "a" }]);
+ const checksSpy = vi.spyOn(consistencyChecks, "runEntityChangesChecks").mockImplementation(() => {});
+ const sectorSpy = vi.spyOn(entityChangesService, "addEntityChangesForSector").mockImplementation(() => {});
+ config.check = [
+ { maxEntityChangeId: 0, entityHashes: { notes: { a: "deadbeef" } } },
+ { maxEntityChangeId: 0, entityHashes: {} }
+ ];
+
+ await expect(runSync()).resolves.toEqual({ success: true });
+ expect(checksSpy).toHaveBeenCalled();
+ expect(sectorSpy).toHaveBeenCalledWith("notes", "a");
+ expect(requestLog.some((r) => r.url.includes("/api/sync/queue-sector/notes/a"))).toBe(true);
+ });
+
+ it("skips the content check while local pushes are still outstanding", async () => {
+ // Inject an outstanding synced change while answering the check request.
+ config.onCheck = (callIndex) => {
+ if (callIndex === 0) {
+ cls.init(() =>
+ getSql().execute(
+ `INSERT INTO entity_changes (entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)
+ VALUES ('notes', 'sync_phantom', 'h', 0, 'phantomChg', 'NA', 'REMOTE_INSTANCE', 1, ?)`,
+ [dateUtils.utcNowDateTime()]
+ )
+ );
+ }
+ };
+ config.check = [
+ { maxEntityChangeId: 0, entityHashes: {} },
+ { maxEntityChangeId: 0, entityHashes: {} }
+ ];
+
+ await expect(runSync()).resolves.toEqual({ success: true });
+ });
+
+ it("tolerates an unserialisable pull response while logging progress", async () => {
+ const circular: Record<string, unknown> = { entityChanges: [pulledOptionChange()], lastEntityChangeId: 3, outstandingPullCount: 0 };
+ circular.self = circular; // JSON.stringify will throw -> the logging catch handles it
+ config.changed = [circular as unknown as ChangesResponse, { entityChanges: [], lastEntityChangeId: 3, outstandingPullCount: 0 }];
+ await expect(runSync()).resolves.toEqual({ success: true });
+ });
+
+ it("fails when a pull request returns no response", async () => {
+ config.changed = [undefined as unknown as ChangesResponse];
+ await expect(runSync()).resolves.toEqual({ success: false, message: "Request failed." });
+ });
+
+ it("fails when the content check returns no response", async () => {
+ config.check = [undefined as unknown as CheckResponse];
+ await expect(runSync()).resolves.toEqual({ success: false, message: "Got no response." });
+ });
+
+ it("reports a connection failure without a stack-trace message", async () => {
+ config.loginThrows = new Error("connect ECONNREFUSED 127.0.0.1:8080");
+ await expect(runSync()).resolves.toEqual({ success: false, message: "No connection to sync server." });
+ });
+
+ it("reports other sync errors with their message", async () => {
+ config.loginThrows = new Error("kaboom");
+ await expect(runSync()).resolves.toEqual({ success: false, message: "kaboom" });
+ });
+
+ describe("login", () => {
+ it("throws when the sync server shares the local instance id", async () => {
+ config.login = { instanceId: getInstanceId(), maxEntityChangeId: 0 };
+ await expect(cls.init(() => syncService.login())).rejects.toThrow(/instance ID/);
+ });
+
+ it("throws when the server returns no response", async () => {
+ config.login = null;
+ await expect(cls.init(() => syncService.login())).rejects.toThrow(/no response/i);
+ });
+
+ it("lowers the last synced pull when it exceeds the server max", async () => {
+ cls.init(() => options.setOption("lastSyncedPull", "999999"));
+ config.login = { instanceId: "REMOTE_INSTANCE", maxEntityChangeId: 7 };
+
+ await cls.init(() => syncService.login());
+ expect(Number(options.getOption("lastSyncedPull"))).toBe(7);
+ });
+
+ it("sends the seed to the server when the schema/seed is missing", async () => {
+ vi.spyOn(setupService, "hasSyncServerSchemaAndSeed").mockResolvedValue(false);
+ const seedSpy = vi.spyOn(setupService, "sendSeedToSyncServer").mockResolvedValue(undefined);
+ config.login = { instanceId: "REMOTE_INSTANCE", maxEntityChangeId: 0 };
+
+ await cls.init(() => syncService.login());
+ expect(seedSpy).toHaveBeenCalled();
+ });
+ });
+
+ describe("getEntityChangeRecords", () => {
+ it("emits a bare record for erased changes and the entity row for normal ones", () => {
+ const noteId = getSql().getValue<string>("SELECT noteId FROM notes WHERE isDeleted = 0 AND noteId <> 'root' LIMIT 1") ?? "root";
+ const records = syncService.getEntityChangeRecords([
+ ec({ entityName: "notes", entityId: noteId }),
+ ec({ entityName: "notes", entityId: "does-not-exist" }),
+ ec({ entityName: "notes", entityId: "ignored", isErased: true })
+ ]);
+
+ // The missing entity is dropped; the real note and the erased marker remain.
+ expect(records.some((r) => r.entityChange.entityId === noteId && r.entity)).toBe(true);
+ expect(records.some((r) => r.entityChange.entityId === "ignored" && !("entity" in r && r.entity))).toBe(true);
+ expect(records.some((r) => r.entityChange.entityId === "does-not-exist")).toBe(false);
+ });
+
+ it("base64-encodes blob content and reads note reordering maps", () => {
+ const blobId = getSql().getValue<string>("SELECT blobId FROM blobs WHERE content IS NOT NULL LIMIT 1") ?? "";
+ const blobRecords = syncService.getEntityChangeRecords([ec({ entityName: "blobs", entityId: blobId })]);
+ const blobEntity = blobRecords[0]?.entity as { content?: unknown } | undefined;
+ expect(typeof blobEntity?.content).toBe("string"); // base64
+
+ const reorder = syncService.getEntityChangeRecords([ec({ entityName: "note_reordering", entityId: "root" })]);
+ expect(reorder[0]?.entity).toBeTypeOf("object");
+ });
+
+ it("throws when an entity type has no primary key", () => {
+ vi.spyOn(entityConstructor, "getEntityFromEntityName").mockReturnValue({ primaryKeyName: "" } as ReturnType<typeof entityConstructor.getEntityFromEntityName>);
+ expect(() => syncService.getEntityChangeRecords([ec({ entityName: "notes", entityId: "root" })])).toThrow(/Unknown entity/);
+ });
+
+ it("stops once the serialized batch exceeds the size limit", () => {
+ const big = "x".repeat(1_100_000);
+ cls.init(() => {
+ getSql().execute("INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('sync_big_blob', ?, ?, ?)", [big, dateUtils.utcNowDateTime(), dateUtils.utcNowDateTime()]);
+ getSql().execute("INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('sync_small_blob', 'y', ?, ?)", [dateUtils.utcNowDateTime(), dateUtils.utcNowDateTime()]);
+ });
+
+ const records = syncService.getEntityChangeRecords([
+ ec({ entityName: "blobs", entityId: "sync_big_blob" }),
+ ec({ entityName: "blobs", entityId: "sync_small_blob" })
+ ]);
+ // The big blob fills the budget so the small one is not included.
+ expect(records).toHaveLength(1);
+ expect(records[0]?.entityChange.entityId).toBe("sync_big_blob");
+ });
+ });
+
+ it("exposes max entity change id and pull counters", () => {
+ expect(typeof syncService.getMaxEntityChangeId()).toBe("number");
+ expect(typeof syncService.getOutstandingPullCount()).toBe("number");
+ // totalPullCount is null between syncs.
+ expect([null, ...Array.from({ length: 0 })]).toContain(syncService.getTotalPullCount());
+ });
+
+ it("startSyncTimer schedules periodic and kickoff syncs once becca is loaded", async () => {
+ // Mock the timer functions so no real sync is ever scheduled (which would
+ // fire during later tests). beccaLoaded is already resolved in the bootstrap,
+ // so its `.then` callback runs on the microtask queue.
+ const setIntervalSpy = vi.spyOn(globalThis, "setInterval").mockReturnValue(0 as unknown as ReturnType<typeof setInterval>);
+ const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout").mockReturnValue(0 as unknown as ReturnType<typeof setTimeout>);
+
+ syncService.startSyncTimer();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 60000);
+ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 5000);
+ });
+});
+
+function pulledOptionChange(): { entityChange: EntityChange; entity: undefined } {
+ // An options change with no entity row -> applied as a no-op by updateEntities.
+ return {
+ entityChange: ec({ entityName: "options", entityId: "sync_spec_noop_opt" }),
+ entity: undefined
+ };
+}
+
+function ec(overrides: Partial<EntityChange>): EntityChange {
+ return {
+ entityName: "notes",
+ entityId: "x",
+ hash: "remote",
+ isErased: false,
+ isSynced: true,
+ utcDateChanged: "2050-01-01 00:00:00.000Z",
+ instanceId: "REMOTE_INSTANCE",
+ ...overrides
+ } as EntityChange;
+}
diff --git a/packages/trilium-core/src/services/sync_update.spec.ts b/packages/trilium-core/src/services/sync_update.spec.ts
new file mode 100644
index 0000000000..821dcd1c8d
--- /dev/null
+++ b/packages/trilium-core/src/services/sync_update.spec.ts
@@ -0,0 +1,187 @@
+import type { EntityChange, EntityChangeRecord, EntityRow } from "@triliumnext/commons";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import * as cls from "./context.js";
+import events from "./events.js";
+import notes from "./notes.js";
+import { getSql } from "./sql/index.js";
+import syncUpdateService from "./sync_update.js";
+import { encodeBase64 } from "./utils/binary.js";
+import dateUtils from "./utils/date.js";
+import ws from "./ws.js";
+
+const FUTURE = "2099-01-01 00:00:00.000Z";
+const PAST = "2000-01-01 00:00:00.000Z";
+
+let counter = 0;
+function createNote(title = "sync-update"): string {
+ counter++;
+ return cls.init(() => notes.createNewNote({
+ parentNoteId: "root",
+ title: `${title}-${counter}`,
+ content: "<p>x</p>",
+ type: "text"
+ }).note.noteId);
+}
+
+function noteRow(noteId: string): EntityRow {
+ const row = getSql().getRowOrNull<EntityRow>("SELECT * FROM notes WHERE noteId = ?", [noteId]);
+ if (!row) throw new Error(`no note row ${noteId}`);
+ return row;
+}
+
+/** A note row with a few columns overridden, cast to the permissive EntityRow shape. */
+function rowWith(noteId: string, extra: Record<string, unknown>): EntityRow {
+ return { ...noteRow(noteId), ...extra } as unknown as EntityRow;
+}
+
+function localHash(entityName: string, entityId: string): string {
+ return getSql().getValue<string>("SELECT hash FROM entity_changes WHERE entityName = ? AND entityId = ?", [entityName, entityId]) ?? "";
+}
+
+function buildEC(overrides: Partial<EntityChange>): EntityChange {
+ return {
+ entityName: "notes",
+ entityId: "x",
+ hash: "remote-hash",
+ isErased: false,
+ isSynced: true,
+ utcDateChanged: FUTURE,
+ ...overrides
+ } as EntityChange;
+}
+
+function apply(records: EntityChangeRecord[], instanceId = "remoteInst") {
+ return cls.init(() => syncUpdateService.updateEntities(records, instanceId));
+}
+
+describe("sync_update service (real DB)", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("returns immediately for an empty change set without signalling a pull", () => {
+ const pullSpy = vi.spyOn(ws, "syncPullInProgress");
+ apply([]);
+ expect(pullSpy).not.toHaveBeenCalled();
+ });
+
+ it("skips changes whose changeId has already been applied", () => {
+ const pullSpy = vi.spyOn(ws, "syncPullInProgress");
+ const noteId = createNote();
+ const changeId = localChangeId("notes", noteId);
+
+ apply([{ entityChange: buildEC({ entityId: noteId, changeId }), entity: noteRow(noteId) }]);
+ // Already-applied change -> no pull signalled.
+ expect(pullSpy).not.toHaveBeenCalled();
+ });
+
+ it("applies a newer remote note, signals a pull and emits ENTITY_CHANGE_SYNCED", () => {
+ const pullSpy = vi.spyOn(ws, "syncPullInProgress");
+ const emitSpy = vi.spyOn(events, "emit");
+ const noteId = createNote();
+ const row = rowWith(noteId, { title: "updated-by-sync" });
+
+ apply([{ entityChange: buildEC({ entityId: noteId, hash: "changed" }), entity: row }], "remoteInstA");
+
+ expect(pullSpy).toHaveBeenCalledOnce();
+ expect(getSql().getValue("SELECT title FROM notes WHERE noteId = ?", [noteId])).toBe("updated-by-sync");
+ expect(getSql().getValue("SELECT instanceId FROM entity_changes WHERE entityName='notes' AND entityId=?", [noteId])).toBe("remoteInstA");
+ expect(emitSpy).toHaveBeenCalledWith(events.ENTITY_CHANGE_SYNCED, expect.objectContaining({ entityName: "notes" }));
+ });
+
+ it("emits ENTITY_DELETE_SYNCED when the synced row is marked deleted", () => {
+ const emitSpy = vi.spyOn(events, "emit");
+ const noteId = createNote();
+ const row = rowWith(noteId, { isDeleted: 1 });
+
+ apply([{ entityChange: buildEC({ entityId: noteId, hash: "changed" }), entity: row }]);
+
+ expect(emitSpy).toHaveBeenCalledWith(events.ENTITY_DELETE_SYNCED, expect.objectContaining({ entityName: "notes", entityId: noteId }));
+ });
+
+ it("erases a note when the remote change is erased and was not erased locally", () => {
+ const noteId = createNote();
+ apply([{ entityChange: buildEC({ entityId: noteId, isErased: true }), entity: undefined }]);
+ expect(getSql().getRowOrNull("SELECT 1 FROM notes WHERE noteId = ?", [noteId])).toBeNull();
+ });
+
+ it("re-erases a note that was already erased locally", () => {
+ const noteId = createNote();
+ cls.init(() => getSql().execute("UPDATE entity_changes SET isErased = 1 WHERE entityName='notes' AND entityId=?", [noteId]));
+
+ apply([{ entityChange: buildEC({ entityId: noteId, isErased: true }), entity: undefined }]);
+ expect(getSql().getRowOrNull("SELECT 1 FROM notes WHERE noteId = ?", [noteId])).toBeNull();
+ });
+
+ it("requeues the change for other instances when the local copy is newer (conflict)", () => {
+ const emitSpy = vi.spyOn(events, "emit");
+ const noteId = createNote();
+ const before = getSql().getValue("SELECT title FROM notes WHERE noteId = ?", [noteId]);
+
+ apply([{ entityChange: buildEC({ entityId: noteId, hash: "different", utcDateChanged: PAST }), entity: rowWith(noteId, { title: "should-not-apply" }) }]);
+
+ // Older remote change is rejected, local row untouched.
+ expect(getSql().getValue("SELECT title FROM notes WHERE noteId = ?", [noteId])).toBe(before);
+ expect(emitSpy).not.toHaveBeenCalledWith(events.ENTITY_CHANGE_SYNCED, expect.anything());
+ });
+
+ it("is a no-op when local and remote are identical but remote is older", () => {
+ const noteId = createNote();
+ const sameHash = localHash("notes", noteId);
+
+ // hash equal + isErased equal (stored as integer 0) + remote older -> falls
+ // through to the final `return false` without re-queuing or applying anything.
+ apply([{ entityChange: buildEC({ entityId: noteId, hash: sameHash, isErased: 0 as unknown as boolean, utcDateChanged: PAST }), entity: noteRow(noteId) }]);
+ expect(getSql().getRowOrNull("SELECT 1 FROM notes WHERE noteId = ?", [noteId])).not.toBeNull();
+ });
+
+ it("applies a note reordering by updating branch positions", () => {
+ const parentNoteId = createNote("reorder-parent");
+ const childBranchId = cls.init(() =>
+ notes.createNewNote({ parentNoteId, title: "child", content: "<p/>", type: "text" }).branch.branchId
+ );
+ if (!childBranchId) throw new Error("child branch missing");
+
+ apply([{ entityChange: buildEC({ entityName: "note_reordering", entityId: parentNoteId }), entity: { [childBranchId]: 77 } as unknown as EntityRow }]);
+
+ expect(getSql().getValue("SELECT notePosition FROM branches WHERE branchId = ?", [childBranchId])).toBe(77);
+ });
+
+ it("decodes base64 blob content (including the empty-buffer special case)", () => {
+ apply([
+ { entityChange: buildEC({ entityName: "blobs", entityId: "su_blob_full" }), entity: blobRow("su_blob_full", encodeBase64("hello")) },
+ { entityChange: buildEC({ entityName: "blobs", entityId: "su_blob_empty" }), entity: blobRow("su_blob_empty", "") }
+ ]);
+
+ const full = getSql().getValue<Buffer | Uint8Array>("SELECT content FROM blobs WHERE blobId = ?", ["su_blob_full"]);
+ expect(Buffer.from(full ?? []).toString()).toBe("hello");
+ const empty = getSql().getValue("SELECT content FROM blobs WHERE blobId = ?", ["su_blob_empty"]);
+ expect(empty === "" || (empty && Buffer.from(empty as Uint8Array).length === 0)).toBeTruthy();
+ });
+
+ it("ignores option changes that have no entity row", () => {
+ // entityName 'options' + no row -> early return, no throw.
+ expect(() => apply([{ entityChange: buildEC({ entityName: "options", entityId: "su_missing_option" }), entity: undefined }])).not.toThrow();
+ });
+
+ it("logs but does not crash when asked to erase an unsupported entity type", () => {
+ // 'options' is not in the eraseable entity list.
+ expect(() => apply([{ entityChange: buildEC({ entityName: "options", entityId: "su_unknown_erase", isErased: true }), entity: { name: "su_unknown_erase", value: "v" } as unknown as EntityRow }])).not.toThrow();
+ });
+
+ it("throws on a normal change missing its entity row", () => {
+ expect(() => apply([{ entityChange: buildEC({ entityId: "su_no_row_note" }), entity: undefined }])).toThrow(/Empty entity row/);
+ });
+
+ it("throws on a note_reordering change missing its body", () => {
+ expect(() => apply([{ entityChange: buildEC({ entityName: "note_reordering", entityId: "su_no_reorder" }), entity: undefined }])).toThrow(/Empty note_reordering body/);
+ });
+});
+
+function localChangeId(entityName: string, entityId: string): string {
+ return getSql().getValue<string>("SELECT changeId FROM entity_changes WHERE entityName = ? AND entityId = ?", [entityName, entityId]) ?? "";
+}
+
+function blobRow(blobId: string, content: string): EntityRow {
+ const now = dateUtils.utcNowDateTime();
+ return { blobId, content, dateModified: now, utcDateModified: now } as unknown as EntityRow;
+}
diff --git a/packages/trilium-core/src/services/ws.spec.ts b/packages/trilium-core/src/services/ws.spec.ts
new file mode 100644
index 0000000000..8fd8048d2f
--- /dev/null
+++ b/packages/trilium-core/src/services/ws.spec.ts
@@ -0,0 +1,226 @@
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import becca from "../becca/becca.js";
+import * as cls from "./context.js";
+import { initMessaging } from "./messaging/index.js";
+import type { ClientMessageHandler } from "./messaging/types.js";
+import protectedSessionService from "./protected_session.js";
+import { getSql } from "./sql/index.js";
+import dateUtils from "./utils/date.js";
+import { randomString } from "./utils/index.js";
+import ws from "./ws.js";
+
+const sentAll: WebSocketMessage[] = [];
+const sentToClient: Array<{ clientId: string; message: WebSocketMessage }> = [];
+let clientHandler: ClientMessageHandler | undefined;
+
+const fakeProvider = {
+ sendMessageToAllClients: vi.fn((message: WebSocketMessage) => {
+ sentAll.push(message);
+ }),
+ sendMessageToClient: vi.fn((clientId: string, message: WebSocketMessage) => {
+ sentToClient.push({ clientId, message });
+ return true;
+ }),
+ setClientMessageHandler: vi.fn((handler: ClientMessageHandler) => {
+ clientHandler = handler;
+ })
+};
+
+function insertEntityChange(entityName: string, entityId: string, isErased = 0): number {
+ return cls.init(() => {
+ getSql().execute(
+ `INSERT INTO entity_changes (entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)
+ VALUES (?, ?, 'hash', ?, ?, 'NA', 'inst', 1, ?)`,
+ [entityName, entityId, isErased, randomString(12), dateUtils.utcNowDateTime()]
+ );
+ return getSql().getValue<number>("SELECT last_insert_rowid()") ?? 0;
+ });
+}
+
+function existingEntityChangeId(entityName: string, entityId: string): number {
+ const id = getSql().getValue<number>(
+ "SELECT id FROM entity_changes WHERE entityName = ? AND entityId = ?",
+ [entityName, entityId]
+ );
+ if (id == null) throw new Error(`no entity_change for ${entityName}/${entityId}`);
+ return id;
+}
+
+// All entity-change ids we drive through buildFrontendUpdateMessage.
+const ecIds: number[] = [];
+
+describe("ws service (real DB)", () => {
+ beforeAll(() => {
+ const now = dateUtils.utcNowDateTime();
+ const blobId = getSql().getValue<string>("SELECT blobId FROM blobs LIMIT 1");
+
+ cls.init(() => {
+ // Protected + plain note rows that becca does not know about (inserted via raw SQL).
+ getSql().execute(
+ `INSERT INTO notes (noteId, title, isProtected, type, mime, isDeleted, dateCreated, dateModified, utcDateCreated, utcDateModified)
+ VALUES ('wsProtNote', 'secret', 1, 'text', 'text/html', 0, ?, ?, ?, ?)`,
+ [now, now, now, now]
+ );
+ getSql().execute(
+ `INSERT INTO notes (noteId, title, isProtected, type, mime, isDeleted, dateCreated, dateModified, utcDateCreated, utcDateModified)
+ VALUES ('wsPlainNote', 'plain', 0, 'text', 'text/html', 0, ?, ?, ?, ?)`,
+ [now, now, now, now]
+ );
+ // Attachments need a matching blob for the JOIN to return a row. They are
+ // marked deleted so becca.getAttachment() (which filters isDeleted=0) misses
+ // them, forcing the DB-fallback path in fillInAdditionalProperties (whose
+ // query has no isDeleted filter).
+ getSql().execute(
+ `INSERT INTO attachments (attachmentId, ownerId, role, mime, title, isProtected, position, blobId, dateModified, utcDateModified, isDeleted)
+ VALUES ('wsProtAtt', 'root', 'file', 'text/plain', 'secret', 1, 0, ?, ?, ?, 1)`,
+ [blobId, now, now]
+ );
+ getSql().execute(
+ `INSERT INTO attachments (attachmentId, ownerId, role, mime, title, isProtected, position, blobId, dateModified, utcDateModified, isDeleted)
+ VALUES ('wsPlainAtt', 'root', 'file', 'text/plain', 'plain', 0, 0, ?, ?, ?, 1)`,
+ [blobId, now, now]
+ );
+ });
+
+ // becca-hit changes (reuse the existing fixture rows).
+ const branchId = becca.getNote("root")?.getChildBranches()[0]?.branchId ?? "root_root";
+ const attrEC = getSql().getRow<{ id: number; entityId: string }>(
+ `SELECT ec.id, ec.entityId FROM entity_changes ec
+ JOIN attributes a ON a.attributeId = ec.entityId
+ WHERE ec.entityName = 'attributes' AND a.isDeleted = 0 LIMIT 1`
+ );
+
+ ecIds.push(
+ existingEntityChangeId("notes", "root"), // becca-hit note
+ existingEntityChangeId("branches", branchId), // becca-hit branch
+ existingEntityChangeId("options", "theme"), // becca-hit option
+ attrEC.id, // becca-hit attribute
+ insertEntityChange("notes", "wsProtNote"), // miss -> protected note row
+ insertEntityChange("notes", "wsPlainNote"), // miss -> plain note row
+ insertEntityChange("notes", "wsMissingNote"), // miss -> no row
+ insertEntityChange("branches", "wsFakeBranch"), // miss
+ insertEntityChange("attributes", "wsFakeAttr"), // miss
+ insertEntityChange("options", "wsFakeOption"), // miss
+ insertEntityChange("attachments", "wsProtAtt"), // miss -> protected attachment row
+ insertEntityChange("attachments", "wsPlainAtt"), // miss -> plain attachment row
+ insertEntityChange("revisions", "wsRev"), // revisions: only sets noteId
+ existingEntityChangeId("note_reordering", "root"), // becca-hit parent with children
+ insertEntityChange("note_reordering", "wsFakeParent"), // miss parent
+ insertEntityChange("notes", "wsErasedNote", 1) // erased -> early return in fillIn
+ );
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it("broadcasts are no-ops before init() wires a provider", () => {
+ const lengthBefore = sentAll.length;
+ ws.syncFinished();
+ cls.init(() => ws.sendTransactionEntityChangesToAllClients());
+ expect(sentAll.length).toBe(lengthBefore);
+ });
+
+ it("init() registers a client message handler routing each message type", async () => {
+ initMessaging(fakeProvider);
+ ws.init();
+ expect(fakeProvider.setClientMessageHandler).toHaveBeenCalled();
+ expect(clientHandler).toBeTypeOf("function");
+
+ const handler = clientHandler;
+ if (!handler) throw new Error("handler not registered");
+
+ await handler("client-1", { type: "log-error", error: "e", stack: "s" });
+ await handler("client-1", { type: "log-info", info: "i" });
+ await handler("client-1", { type: "ping" });
+ await handler("client-1", { type: "totally-unknown" });
+
+ expect(sentToClient).toContainEqual({ clientId: "client-1", message: { type: "ping" } });
+ });
+
+ it("sync status helpers broadcast the matching message types with lastSyncedPush", () => {
+ ws.setLastSyncedPush(42);
+ ws.syncPushInProgress();
+ ws.syncPullInProgress();
+ ws.syncFinished();
+ ws.syncFailed();
+ ws.reloadFrontend("because");
+
+ const types = sentAll.map((m) => m.type);
+ expect(types).toEqual(expect.arrayContaining([
+ "sync-push-in-progress",
+ "sync-pull-in-progress",
+ "sync-finished",
+ "sync-failed",
+ "reload-frontend"
+ ]));
+ const pull = sentAll.find((m) => m.type === "sync-pull-in-progress");
+ expect(pull).toMatchObject({ lastSyncedPush: 42 });
+ });
+
+ it("sends a ping frontend-update when there are no pending entity changes", () => {
+ const before = sentAll.length;
+ cls.init(() => ws.sendTransactionEntityChangesToAllClients());
+ expect(sentAll[sentAll.length - 1]).toEqual({ type: "ping" });
+ expect(sentAll.length).toBe(before + 1);
+ });
+
+ it("builds a frontend-update message filling in properties for every entity type", () => {
+ cls.init(() => {
+ cls.set("entityChangeIds", [...ecIds]);
+ ws.sendTransactionEntityChangesToAllClients();
+ });
+
+ const message = sentAll[sentAll.length - 1];
+ expect(message.type).toBe("frontend-update");
+ if (message.type !== "frontend-update") throw new Error("expected frontend-update");
+
+ const changes = message.data.entityChanges;
+ // Every entity type should have been processed.
+ const byName = new Map<string, unknown>();
+ for (const c of changes) byName.set(c.entityName, c);
+ expect(byName.has("notes")).toBe(true);
+ expect(byName.has("branches")).toBe(true);
+ expect(byName.has("attributes")).toBe(true);
+ expect(byName.has("options")).toBe(true);
+ expect(byName.has("attachments")).toBe(true);
+ expect(byName.has("note_reordering")).toBe(true);
+
+ // becca-hit note got its full pojo (title present).
+ const rootChange = changes.find((c) => c.entityName === "notes" && c.entityId === "root");
+ expect(rootChange?.entity).toMatchObject({ noteId: "root" });
+
+ // note_reordering for root carries the child branch positions map.
+ const reorder = changes.find((c) => c.entityName === "note_reordering" && c.entityId === "root");
+ expect(reorder?.positions).toBeTypeOf("object");
+ });
+
+ it("swallows errors thrown while filling in a single entity change", () => {
+ vi.spyOn(protectedSessionService, "decryptString").mockImplementation(() => {
+ throw new Error("decrypt failed");
+ });
+ const protId = existingEntityChangeId("notes", "wsProtNote");
+
+ const before = sentAll.length;
+ expect(() =>
+ cls.init(() => {
+ cls.set("entityChangeIds", [protId]);
+ ws.sendTransactionEntityChangesToAllClients();
+ })
+ ).not.toThrow();
+ // The message is still sent despite the per-entity error.
+ expect(sentAll.length).toBe(before + 1);
+ });
+
+ it("does not send when the entity changes query yields no rows", () => {
+ const sql = getSql();
+ vi.spyOn(sql, "getManyRows").mockReturnValueOnce(undefined as never);
+
+ const before = sentAll.length;
+ cls.init(() => {
+ cls.set("entityChangeIds", [ecIds[0]]);
+ ws.sendTransactionEntityChangesToAllClients();
+ });
+ expect(sentAll.length).toBe(before);
+ });
+});