Skip to content

Build your personal knowledge base with Trilium Notes

test(setup): cover the wizard failure flow and remaining patch branches

Elian Doran8a0af1ec8e0b
diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsx
new file mode 100644
index 0000000000..19915a6520
--- /dev/null
+++ b/apps/client/src/setup.spec.tsx
@@ -0,0 +1,198 @@
+import { render } from "preact";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// t() returns the key so assertions are deterministic and not tied to English text.
+vi.mock("./services/i18n", () => ({
+ t: (key: string) => key,
+ initLocale: vi.fn(),
+ getCurrentLanguage: () => "en"
+}));
+
+const serverMock = vi.hoisted(() => ({
+ // Default implementation serves the module-load-time requests transitively imported
+ // modules fire (e.g. keyboard_actions fetches its shortcut list on import) — the
+ // per-test routing installed in beforeEach overrides it.
+ get: vi.fn(async (url: string) => {
+ if (url === "keyboard-actions") {
+ return [];
+ }
+ return {};
+ }),
+ post: vi.fn(async () => ({}))
+}));
+vi.mock("./services/server", () => ({ default: serverMock }));
+
+import { renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";
+
+type Stats = { outstandingPullCount: number; totalPullCount: number | null; initialized: boolean; lastSyncError?: string | null };
+
+let container: HTMLDivElement;
+function renderInto(vnode: preact.ComponentChild) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ render(vnode, container);
+ return container;
+}
+
+// Preact flushes effects via requestAnimationFrame (~16ms under fake timers), so
+// "flushing" means advancing past that; a poll tick is the hook's 1s interval on top.
+const flushEffects = () => vi.advanceTimersByTimeAsync(50);
+const nextPoll = () => vi.advanceTimersByTimeAsync(1000);
+
+/** Routes the mocked server.get; `stats` can be swapped between polls. */
+let stats: Stats;
+function mockRoutes(extra: Record<string, unknown> = {}) {
+ serverMock.get.mockImplementation(async (url: string) => {
+ if (url === "sync/stats") {
+ return stats;
+ }
+ return extra[url];
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ stats = { outstandingPullCount: 0, totalPullCount: null, initialized: false, lastSyncError: null };
+ mockRoutes();
+ serverMock.post.mockResolvedValue({});
+});
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+describe("SyncInProgress", () => {
+ it("switches to the failure screen when the server reports a failed sync", async () => {
+ const setState = vi.fn();
+ stats = { ...stats, lastSyncError: "401 Logged in session not found" };
+ renderInto(<SyncInProgress device="server" setState={setState} />);
+ await flushEffects();
+ expect(setState).toHaveBeenCalledWith("syncFailed");
+ });
+
+ it("ignores sync errors in the sync-from-desktop flow (the other device syncs, not us)", async () => {
+ const setState = vi.fn();
+ stats = { ...stats, lastSyncError: "boom" };
+ renderInto(<SyncInProgress device="desktop" setState={setState} />);
+ await flushEffects();
+ expect(setState).not.toHaveBeenCalled();
+ });
+
+ it("stays on the progress screen while the sync is healthy", async () => {
+ const setState = vi.fn();
+ renderInto(<SyncInProgress device="server" setState={setState} />);
+ await flushEffects();
+ expect(setState).not.toHaveBeenCalled();
+ });
+
+ it("is wired for both flows in renderState", async () => {
+ for (const state of ["syncFromServerInProgress", "syncFromDesktopInProgress"] as const) {
+ const c = renderInto(renderState(state, vi.fn()));
+ await flushEffects();
+ expect(c.querySelector(".page.sync-in-progress")).not.toBeNull();
+ render(null, c);
+ c.remove();
+ }
+ });
+});
+
+describe("SyncFailed", () => {
+ it("shows the recorded error and a hint, and renderState wires the syncFailed case", async () => {
+ stats = { ...stats, lastSyncError: "Request to PUT https://[redacted]/api/sync/update failed" };
+ const c = renderInto(renderState("syncFailed", vi.fn()));
+ await flushEffects();
+
+ const pre = c.querySelector(".admonition-body pre");
+ expect(pre?.textContent).toBe("Request to PUT https://[redacted]/api/sync/update failed");
+ expect(c.querySelector(".admonition-body p")?.textContent).toBe("setup.sync-failed-hint");
+ });
+
+ it("retries via sync/now and hands back to the progress screen once the attempt starts", async () => {
+ const setState = vi.fn();
+ stats = { ...stats, lastSyncError: "boom" };
+ const c = renderInto(<SyncFailed setState={setState} />);
+ await flushEffects();
+
+ const retry = [...c.querySelectorAll("button")].find((b) => b.textContent?.includes("setup.button-retry"));
+ expect(retry).toBeDefined();
+ retry?.click();
+ expect(serverMock.post).toHaveBeenCalledWith("sync/now");
+
+ // The server clears the error as the new attempt starts; the next poll notices.
+ stats = { ...stats, lastSyncError: null };
+ await nextPoll();
+ expect(setState).toHaveBeenCalledWith("syncFromServerInProgress");
+ });
+
+ it("finishes setup directly when the retry converges before the next transition", async () => {
+ const reload = vi.spyOn(window.location, "reload").mockImplementation(() => {});
+ const setState = vi.fn();
+ stats = { ...stats, lastSyncError: "boom" };
+ renderInto(<SyncFailed setState={setState} />);
+ await flushEffects();
+
+ stats = { ...stats, lastSyncError: null, initialized: true };
+ await nextPoll();
+ expect(reload).toHaveBeenCalled();
+ expect(setState).not.toHaveBeenCalledWith("syncFromServerInProgress");
+ });
+
+ it("goes back to the server form", async () => {
+ const setState = vi.fn();
+ stats = { ...stats, lastSyncError: "boom" };
+ const c = renderInto(<SyncFailed setState={setState} />);
+ await flushEffects();
+
+ const back = [...c.querySelectorAll("button")].find((b) => b.textContent?.includes("setup.button-back"));
+ back?.click();
+ expect(setState).toHaveBeenCalledWith("syncFromServer");
+ });
+});
+
+describe("SyncFromServer", () => {
+ it("prefills the stored server address and proxy after a failed attempt", async () => {
+ mockRoutes({ "setup/status": { syncServerHost: "https://old.example.com", syncProxy: "http://proxy:3128" } });
+ const c = renderInto(<SyncFromServer setState={vi.fn()} />);
+ await flushEffects();
+
+ const inputs = [...c.querySelectorAll("input")];
+ expect(inputs.some((i) => i.value === "https://old.example.com")).toBe(true);
+ expect(inputs.some((i) => i.value === "http://proxy:3128")).toBe(true);
+ });
+
+ it("does not clobber a value the user already typed before the prefill resolves", async () => {
+ let resolveStatus: (v: unknown) => void = () => {};
+ serverMock.get.mockImplementation((url: string) => {
+ if (url === "setup/status") {
+ return new Promise((resolve) => {
+ resolveStatus = resolve;
+ });
+ }
+ return Promise.resolve(stats);
+ });
+ const c = renderInto(<SyncFromServer setState={vi.fn()} />);
+
+ const host = c.querySelector<HTMLInputElement>("input");
+ expect(host).not.toBeNull();
+ if (!host) return;
+ host.value = "https://typed.example.com";
+ host.dispatchEvent(new Event("input", { bubbles: true }));
+
+ resolveStatus({ syncServerHost: "https://stored.example.com", syncProxy: "" });
+ await flushEffects();
+
+ expect(host.value).toBe("https://typed.example.com");
+ });
+
+ it("leaves the form empty on a fresh setup (no stored sync options)", async () => {
+ mockRoutes({ "setup/status": { isInitialized: false, schemaExists: false } });
+ const c = renderInto(<SyncFromServer setState={vi.fn()} />);
+ await flushEffects();
+
+ const host = c.querySelector<HTMLInputElement>("input");
+ expect(host?.value).toBe("");
+ });
+});
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsx
index fd49cf0b9f..405afae32c 100644
--- a/apps/client/src/setup.tsx
+++ b/apps/client/src/setup.tsx
@@ -36,7 +36,7 @@ type State = "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "c
const STATE_ORDER: State[] = ["selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];
-function renderState(state: State, setState: (state: State) => void) {
+export function renderState(state: State, setState: (state: State) => void) {
switch (state) {
case "selectLanguage": return <SelectLanguage setState={setState} />;
case "firstOptions": return <SetupOptions setState={setState} />;
@@ -228,7 +228,7 @@ function useWakeLock() {
}, []);
}
-function SyncInProgress({ device, setState }: { device: "server" | "desktop"; setState: (state: State) => void }) {
+export function SyncInProgress({ device, setState }: { device: "server" | "desktop"; setState: (state: State) => void }) {
const stats = useOutstandingSyncInfo();
const step = getSyncStep(stats);
useWakeLock();
@@ -296,7 +296,7 @@ function SyncInProgress({ device, setState }: { device: "server" | "desktop"; se
);
}
-function SyncFailed({ setState }: { setState: (state: State) => void }) {
+export function SyncFailed({ setState }: { setState: (state: State) => void }) {
const stats = useOutstandingSyncInfo();
// Freeze the last seen error: when a retry starts, the server clears it before the
// attempt runs, and the text must not blank out while this page transitions away.
@@ -406,7 +406,7 @@ function CreateNewDocumentInProgress({ withDemo = false }: { withDemo?: boolean
);
}
-function SyncFromServer({ setState }: { setState: (state: State) => void }) {
+export function SyncFromServer({ setState }: { setState: (state: State) => void }) {
const [ syncServerHost, setSyncServerHost ] = useState("");
const [ password, setPassword ] = useState("");
const [ syncProxy, setSyncProxy ] = useState("");
@@ -672,4 +672,7 @@ function onSetupFinished() {
}
}
-main();
+// Skip the bootstrap render under test, where the components are imported directly.
+if (import.meta.env.MODE !== "test") {
+ void main();
+}
diff --git a/packages/trilium-core/src/routes/api/setup.spec.ts b/packages/trilium-core/src/routes/api/setup.spec.ts
index d410b6630a..07d395ef73 100644
--- a/packages/trilium-core/src/routes/api/setup.spec.ts
+++ b/packages/trilium-core/src/routes/api/setup.spec.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import appInfo from "../../services/app_info";
+import optionService from "../../services/options";
import setupService from "../../services/setup";
import sqlInit from "../../services/sql_init";
import { CoreApiTester } from "../../test/api_tester";
@@ -46,6 +47,14 @@ describe("Setup API (core)", () => {
expect(res.body.syncServerHost).toBeUndefined();
});
+ it("falls back to empty strings when the sync options are absent", async () => {
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
+ vi.spyOn(optionService, "getOptionOrNull").mockReturnValue(null);
+ const res = await api.get<{ syncServerHost?: string; syncProxy?: string }>("/api/setup/status");
+ expect(res.body.syncServerHost).toBe("");
+ expect(res.body.syncProxy).toBe("");
+ });
+
it("creates a new document (createInitialDatabase stubbed)", async () => {
const createInitial = vi.spyOn(sqlInit, "createInitialDatabase").mockResolvedValue(undefined);
const res = await api.post("/api/setup/new-document", { query: { skipDemoDb: "1" } });
diff --git a/packages/trilium-core/src/services/sql_init_resetup.spec.ts b/packages/trilium-core/src/services/sql_init_resetup.spec.ts
index c07d1a3a7b..bb9611254c 100644
--- a/packages/trilium-core/src/services/sql_init_resetup.spec.ts
+++ b/packages/trilium-core/src/services/sql_init_resetup.spec.ts
@@ -29,6 +29,8 @@ describe("createDatabaseForSync on a partially set-up database", () => {
expect(sqlInit.isDbInitialized()).toBe(false);
const staleNoteCount = sql.getValue<number>("SELECT COUNT(*) FROM notes") ?? 0;
expect(staleNoteCount).toBeGreaterThan(0);
+ // Views must be wiped through DROP VIEW, not DROP TABLE.
+ sql.execute("CREATE VIEW stale_view AS SELECT 1 AS x");
// cls.init mirrors the route context this runs under in production.
await cls.init(() => sqlInit.createDatabaseForSync(
@@ -42,6 +44,7 @@ describe("createDatabaseForSync on a partially set-up database", () => {
// The schema is back and pristine: no leftovers from the previous partial pull.
expect(sqlInit.schemaExists()).toBe(true);
expect(sql.getValue<number>("SELECT COUNT(*) FROM notes")).toBe(0);
+ expect(sql.getValue<number>("SELECT COUNT(*) FROM sqlite_master WHERE name = 'stale_view'")).toBe(0);
// The new seed and sync options won.
expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'documentId'")).toBe("resetup-doc-id");
@@ -66,4 +69,26 @@ describe("createDatabaseForSync on a partially set-up database", () => {
expect(sql.getValue<number>("SELECT COUNT(*) FROM notes WHERE noteId = 'root'")).toBe(1);
expect(sql.getValue<number>("SELECT COUNT(*) FROM notes WHERE noteId = 'stalePulled1'")).toBe(0);
});
+
+ it("is a no-op wipe on a virgin database (no schema at all)", async () => {
+ const sql = getSql();
+
+ // Reduce the DB to a truly empty file, as on a first-ever run.
+ sql.execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");
+ const objects = sql.getRows<{ name: string; type: string }>(
+ /*sql*/`SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%'`
+ );
+ for (const { name, type } of objects) {
+ sql.execute(`DROP ${type === "view" ? "VIEW" : "TABLE"} IF EXISTS "${name}"`);
+ }
+ expect(sqlInit.schemaExists()).toBe(false);
+
+ await cls.init(() => sqlInit.createDatabaseForSync(
+ [{ name: "documentSecret", value: "virgin-secret", isSynced: true, utcDateModified: "2026-07-18 00:00:00.000Z" }],
+ "http://sync-server:8080"
+ ));
+
+ expect(sqlInit.schemaExists()).toBe(true);
+ expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'documentSecret'")).toBe("virgin-secret");
+ });
});