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
fix(setup): surface failed initial sync in the wizard instead of hanging forever
Elian Doran07d460ffa043
diff --git a/apps/client/src/setup.css b/apps/client/src/setup.cssindex 3362c79b7a..1daa51c23c 100644--- a/apps/client/src/setup.css+++ b/apps/client/src/setup.css@@ -502,6 +502,21 @@ body[dir=rtl] .slide-in-backward {}}+.page.sync-failed {+ .admonition-body pre {+ /* Sync errors embed full request URLs — wrap instead of overflowing the card. */+ white-space: pre-wrap;+ word-break: break-word;+ margin: 0 0 0.5rem;+ }++ .admonition-body p {+ margin: 0;+ color: var(--muted-text-color);+ font-size: 0.9em;+ }+}+@keyframes slide-out-left {from { transform: translateX(0); opacity: 1; }to { transform: translateX(-100%); opacity: 0; }diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex 5cd30f7205..9229af523e 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -45,8 +45,9 @@ function renderState(state: State, setState: (state: State) => void) {case "createNewDocumentEmpty": return <CreateNewDocumentInProgress />;case "syncFromServer": return <SyncFromServer setState={setState} />;case "syncFromDesktop": return <SyncFromDesktop setState={setState} />;- case "syncFromServerInProgress": return <SyncInProgress device="server" />;- case "syncFromDesktopInProgress": return <SyncInProgress device="desktop" />;+ case "syncFromServerInProgress": return <SyncInProgress device="server" setState={setState} />;+ case "syncFromDesktopInProgress": return <SyncInProgress device="desktop" setState={setState} />;+ case "syncFailed": return <SyncFailed setState={setState} />;default: return null;}}@@ -227,7 +228,7 @@ function useWakeLock() {}, []);}-function SyncInProgress({ device }: { device: "server" | "desktop" }) {+function SyncInProgress({ device, setState }: { device: "server" | "desktop"; setState: (state: State) => void }) {const stats = useOutstandingSyncInfo();const step = getSyncStep(stats);useWakeLock();@@ -238,6 +239,14 @@ function SyncInProgress({ device }: { device: "server" | "desktop" }) {}}, [stats.initialized]);+ useEffect(() => {+ // Only the sync-from-server flow runs sync attempts on this instance; in the+ // sync-from-desktop flow the OTHER device pushes to us, so no local error can occur.+ if (device === "server" && stats.lastSyncError && !stats.initialized) {+ setState("syncFailed");+ }+ }, [device, stats.lastSyncError, stats.initialized, setState]);+const steps: { key: SyncStep; label: string }[] = [{ key: "connecting", label: t("setup.sync-step-connecting") },{ key: "syncing", label: t("setup.sync-step-syncing") },@@ -287,16 +296,74 @@ function SyncInProgress({ device }: { device: "server" | "desktop" }) {);}+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.+ const [ message, setMessage ] = useState<string | null>(null);++ useEffect(() => {+ if (stats.initialized) {+ // The retry converged before we even switched back to the progress screen.+ onSetupFinished();+ } else if (stats.lastSyncError) {+ setMessage(stats.lastSyncError);+ } else if (message !== null) {+ // The error was cleared server-side — a new sync attempt is underway, so hand+ // back to the progress screen. Driven by the polled server state rather than the+ // button click, which avoids racing the sync/now request against the next poll.+ setState("syncFromServerInProgress");+ }+ }, [stats.lastSyncError, stats.initialized, message, setState]);++ return (+ <SetupPage+ className="sync-failed"+ title={t("setup.sync-failed-title")}+ description={t("setup.sync-failed-description")}+ illustration={<Icon icon="bx bx-error-circle" className="illustration-icon" />}+ onBack={() => setState("syncFromServer")}+ footer={+ <Button+ text={t("setup.button-retry")}+ kind="primary"+ icon="bx bx-refresh"+ onClick={() => {+ // Fire-and-forget: the polling effect above notices the attempt+ // starting (error cleared) and switches to the progress screen.+ server.post("sync/now").catch(() => {});+ }}+ />+ }+ >+ {message && (+ <ExtendedAdmonition+ type="caution"+ icon="bx bx-error-circle"+ title={t("setup.sync-failed-admonition-title")}+ >+ {/* Kept fully visible (not collapsed): bug reports are often just a+ screenshot of this screen, and the raw error is what matters. */}+ <pre>{message}</pre>+ <p>{t("setup.sync-failed-hint")}</p>+ </ExtendedAdmonition>+ )}+ </SetupPage>+ );+}+function useOutstandingSyncInfo() {const [ outstandingPullCount, setOutstandingPullCount ] = useState(0);const [ totalPullCount, setTotalPullCount ] = useState<number | null>(null);const [ initialized, setInitialized ] = useState(false);+ const [ lastSyncError, setLastSyncError ] = useState<string | null>(null);async function refresh() {- const resp = await server.get<{ outstandingPullCount: number; totalPullCount: number | null; initialized: boolean }>("sync/stats");+ const resp = await server.get<{ outstandingPullCount: number; totalPullCount: number | null; initialized: boolean; lastSyncError?: string | null }>("sync/stats");setOutstandingPullCount(resp.outstandingPullCount);setTotalPullCount(resp.totalPullCount);setInitialized(resp.initialized);+ setLastSyncError(resp.lastSyncError ?? null);}useEffect(() => {@@ -305,7 +372,7 @@ function useOutstandingSyncInfo() {return () => clearInterval(interval);}, []);- return { outstandingPullCount, totalPullCount, initialized };+ return { outstandingPullCount, totalPullCount, initialized, lastSyncError };}function CreateNewDocumentOptions({ setState }: { setState: (state: State) => void }) {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 23aac9f7fe..dd920af36a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3093,7 +3093,12 @@"sync-from-desktop-unreachable-description": "To sync, the other desktop has to connect to this one over the network. For security, this desktop app only accepts connections from this computer, so that other desktop can't reach it yet. Allow network access below — Trilium will restart to apply it.","sync-from-desktop-allow-access": "Allow network access & restart","advanced-options": "Advanced options",- "sync-failed": "Failed to sync: {{message}}",+ "sync-failed": "Failed to sync: {{- message}}",+ "sync-failed-title": "Sync failed",+ "sync-failed-description": "The initial synchronization could not be completed. You can retry, or go back to check the server address and credentials.",+ "sync-failed-admonition-title": "The last sync attempt failed",+ "sync-failed-hint": "This can be caused by a wrong server address, a proxy interfering with the connection, or the server being temporarily unreachable.",+ "button-retry": "Retry","server-host": "Trilium server address","server-host-placeholder": "https://<hostname>:<port>","server-password": "Password",diff --git a/apps/server/spec/sync/sync-protocol.spec.ts b/apps/server/spec/sync/sync-protocol.spec.tsnew file mode 100644index 0000000000..8096fbc956--- /dev/null+++ b/apps/server/spec/sync/sync-protocol.spec.ts@@ -0,0 +1,161 @@+/**+ * End-to-end test of the sync protocol as the desktop client drives it, with the+ * built-in OIDC (OAuth) sign-in method enabled on the server — regression test for+ * https://github.com/TriliumNext/Trilium/issues/10548.+ *+ * The desktop sync client authenticates via an HMAC handshake (`POST /api/login/sync`)+ * and then replays the raw `Set-Cookie` value (attributes included) as its `Cookie`+ * header for the follow-up `/api/sync/*` requests (see the cookie jar in+ * `apps/server/src/services/request.ts`). This suite drives that exact exchange through+ * the real Express app — session parser, reactive OIDC middleware and route registration+ * included — to pin down that:+ *+ * 1. the express-openid-connect middleware passes `/api/*` requests through untouched+ * even when OAuth is configured and active, and+ * 2. sync responses carry exactly ONE cookie (`trilium.sid`). This is what keeps the+ * desktop jar working: Electron's `net` module serializes an array-valued `Cookie`+ * header by `Array.prototype.toString()` — a bare-comma join — so a second+ * Set-Cookie in any response (e.g. a reverse-proxy affinity cookie) merges into the+ * previous cookie's attributes on replay and destroys the session cookie.+ */+import { app_info as appInfo, cls, date_utils as dateUtils, options } from "@triliumnext/core";+import type { Application } from "express";+import supertest from "supertest";+import { beforeAll, describe, expect, it } from "vitest";++import { refreshAuth } from "../../src/services/auth.js";+import config from "../../src/services/config.js";+import utils from "../../src/services/utils.js";++let app: Application;++describe("sync protocol with built-in OIDC enabled (#10548)", () => {+ beforeAll(async () => {+ // The spec config.ini runs with noAuthentication=true; sync auth is only exercised+ // with real authentication on. refreshAuth() re-reads the flag into auth.ts's cache.+ config.General.noAuthentication = false;+ refreshAuth();++ // Configure OAuth as a real OIDC deployment would (config.ini / env vars) and select+ // it as the sign-in method. The issuer is deliberately unreachable: plain API requests+ // never trigger provider discovery, mirroring an unattended desktop syncing against an+ // OIDC-protected server, and the RP-Initiated-Logout probe degrades gracefully.+ config.MultiFactorAuthentication.oauthBaseUrl = "http://localhost:4200";+ config.MultiFactorAuthentication.oauthClientId = "spec-client";+ config.MultiFactorAuthentication.oauthClientSecret = "a-very-long-spec-only-oauth-secret-0123456789";+ config.MultiFactorAuthentication.oauthIssuerBaseUrl = "http://127.0.0.1:1";+ cls.init(() => options.setOption("mfaMethod", "oauth"));++ const buildApp = (await import("../../src/app.js")).default;+ app = await buildApp();+ });++ it("engages the OIDC middleware (sanity check that this suite tests what it claims)", async () => {+ // /authenticate only exists inside the express-openid-connect router. When the+ // reactive middleware is active it handles the route (and errors with 500 because+ // the issuer above is unreachable); were OAuth unconfigured, the request would fall+ // through to the 404 handler and this suite would silently test nothing.+ const res = await supertest(app).get("/authenticate");+ expect(res.status).toBe(500);+ });++ it("performs the full desktop sync round-trip: login, push, pull, finished", async () => {+ const sessionCookie = await syncLogin();++ // The login response must set exactly one cookie: the session. A second Set-Cookie+ // on any sync response breaks the desktop client (see file header) — this is the+ // server-side guarantee that keeps the Electron cookie jar functional.+ expect(sessionCookie).toMatch(/^trilium\.sid=/);++ // push — the request that 401s in #10548+ await supertest(app)+ .put("/api/sync/update?logMarkerId=spec")+ .set("Cookie", sessionCookie)+ .set("pageCount", "1")+ .set("pageIndex", "0")+ .send({ entities: [], instanceId: "spec-desktop" })+ .expect(204);++ // pull+ const changed = await supertest(app)+ .get("/api/sync/changed?instanceId=spec-desktop&lastEntityChangeId=0&logMarkerId=spec")+ .set("Cookie", sessionCookie)+ .expect(200);+ expect(changed.body.entityChanges).toBeDefined();++ await supertest(app)+ .post("/api/sync/finished")+ .set("Cookie", sessionCookie)+ .expect(204);+ });++ it("rejects sync requests without the session cookie", async () => {+ const res = await supertest(app)+ .put("/api/sync/update?logMarkerId=spec")+ .set("pageCount", "1")+ .set("pageIndex", "0")+ .send({ entities: [], instanceId: "spec-desktop" });+ expect(res.status).toBe(401);+ expect(res.text).toBe("Logged in session not found");+ });++ it("allows the setup wizard to trigger sync/now without a CSRF token while the DB is uninitialized", async () => {+ // Pre-initialization, SQLiteSessionStore no-ops, so every request gets a fresh+ // session id — and csrf-csrf binds tokens to the session id, meaning CSRF+ // validation can NEVER pass during setup. The wizard's resume/retry sync/now+ // call used to die on 403 "Invalid CSRF token" (silently — the client swallowed+ // it), leaving a failed initial sync stuck forever. CSRF also protects nothing+ // here: before initialization there is no authenticated session to ride.+ const sql = (await import("../../src/services/sql.js")).default;+ sql.execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");+ try {+ const res = await supertest(app).post("/api/sync/now");+ expect(res.status).toBe(200);+ // No sync options configured on the fixture — the request must reach the+ // handler (proving CSRF was bypassed) and report not-configured.+ expect(res.body.errorCode).toBe("NOT_CONFIGURED");+ } finally {+ sql.execute("UPDATE options SET value = 'true' WHERE name = 'initialized'");+ }+ });++ it("loses the session when a foreign cookie precedes trilium.sid in a comma-joined Cookie header (#10548 mechanism)", async () => {+ const sessionCookie = await syncLogin();++ // This is byte-for-byte what the server receives from the desktop when a response+ // carried two Set-Cookie headers (proxy affinity cookie first): the jar stores the+ // array and Electron's net joins it with a bare comma, so trilium.sid gets swallowed+ // into the preceding cookie's attributes ("HttpOnly,trilium.sid" is not a valid key).+ // The 401 is correct server behavior — the fix for #10548 belongs in the client jar —+ // but this documents the exact failure reported in the issue.+ const mangled = `INGRESSCOOKIE=abc123; Path=/; Secure; HttpOnly,${sessionCookie}`;+ const res = await supertest(app)+ .put("/api/sync/update?logMarkerId=spec")+ .set("Cookie", mangled)+ .set("pageCount", "1")+ .set("pageIndex", "0")+ .send({ entities: [], instanceId: "spec-desktop" });+ expect(res.status).toBe(401);+ expect(res.text).toBe("Logged in session not found");+ });+});++/**+ * Performs the HMAC sync login and returns the raw Set-Cookie value — attributes and all —+ * exactly as the desktop cookie jar stores and replays it.+ */+async function syncLogin(): Promise<string> {+ const timestamp = dateUtils.utcNowDateTime();+ const documentSecret = options.getOption("documentSecret");+ const hash = utils.hmac(documentSecret, timestamp);++ const res = await supertest(app)+ .post("/api/login/sync")+ .send({ timestamp, syncVersion: appInfo.syncVersion, hash })+ .expect(200);+ expect(res.body.instanceId).toBeTruthy();++ const setCookie: string[] = res.headers["set-cookie"] ?? [];+ expect(setCookie).toHaveLength(1);+ return setCookie[0];+}diff --git a/apps/server/src/routes/csrf_protection.ts b/apps/server/src/routes/csrf_protection.tsindex 2098a95851..fb1e22fa28 100644--- a/apps/server/src/routes/csrf_protection.ts+++ b/apps/server/src/routes/csrf_protection.ts@@ -4,6 +4,7 @@ import type { NextFunction, Request, Response } from "express";import { isInternalElectronRequest } from "../services/electron_request.js";import sessionSecret from "../services/session_secret.js";import config from "../services/config.js";+import sqlInit from "../services/sql_init.js";export const CSRF_COOKIE_NAME = "trilium-csrf";@@ -32,5 +33,13 @@ export function doubleCsrfProtection(req: Request, res: Response, next: NextFuncif (isInternalElectronRequest(req)) {return next();}+ // Before the DB is initialized, sessions are never persisted (SQLiteSessionStore+ // no-ops), so every request carries a fresh session id and the session-bound CSRF+ // token can never validate — protected endpoints the setup wizard needs (sync/now+ // for resume/retry of the initial sync) would always 403. CSRF also has nothing to+ // protect at this stage: there is no authenticated session to ride. See #10548.+ if (!sqlInit.isDbInitialized()) {+ return next();+ }return doubleCsrfUtilities.doubleCsrfProtection(req, res, next);}diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.tsindex 159b7ff629..83a93cebbf 100644--- a/packages/trilium-core/src/routes/api/sync.spec.ts+++ b/packages/trilium-core/src/routes/api/sync.spec.ts@@ -79,6 +79,29 @@ describe("Sync API (core)", () => {expect(res.status).toBe(200);expect(res.body).toEqual({});});++ it("exposes the last sync error while the DB is not yet initialized (setup wizard)", async () => {+ vi.spyOn(syncService, "getLastSyncError").mockReturnValue("401 Logged in session not found");+ const prevInitialized = optionService.getOption("initialized");+ getSql().execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");+ try {+ const res = await api.get<{ initialized: boolean; lastSyncError: string | null }>("/api/sync/stats");+ expect(res.status).toBe(200);+ expect(res.body.initialized).toBe(false);+ expect(res.body.lastSyncError).toBe("401 Logged in session not found");+ } finally {+ getSql().execute("UPDATE options SET value = ? WHERE name = 'initialized'", [prevInitialized]);+ }+ });++ it("does not expose sync errors once initialized — the stats endpoint is unauthenticated", async () => {+ vi.spyOn(syncService, "getLastSyncError").mockReturnValue("must stay private");++ const res = await api.get<{ initialized: boolean; lastSyncError?: string }>("/api/sync/stats");+ expect(res.status).toBe(200);+ expect(res.body.initialized).toBe(true);+ expect(res.body.lastSyncError).toBeUndefined();+ });});it("checkSync returns entity hashes and the max entity change id", async () => {diff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.tsindex ced73200cd..caece8876d 100644--- a/packages/trilium-core/src/routes/api/sync.ts+++ b/packages/trilium-core/src/routes/api/sync.ts@@ -44,10 +44,15 @@ function getStats() {return {};}+ const initialized = getSql().getValue("SELECT value FROM options WHERE name = 'initialized'") === "true";const stats = {- initialized: getSql().getValue("SELECT value FROM options WHERE name = 'initialized'") === "true",+ initialized,outstandingPullCount: syncService.getOutstandingPullCount(),- totalPullCount: syncService.getTotalPullCount()+ totalPullCount: syncService.getTotalPullCount(),+ // Lets the setup wizard's progress screen detect a failed initial sync (#10548).+ // Only exposed pre-initialization: this endpoint is unauthenticated, so once the+ // instance is up and running, sync errors must not leak to anonymous visitors.+ ...(initialized ? {} : { lastSyncError: syncService.getLastSyncError() })};getLog().info(`Returning sync stats: ${JSON.stringify(stats)}`);diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex c0fd7f3526..634c568737 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -262,6 +262,21 @@ async function createDatabaseForSync(options: OptionRow[], syncServerHost = "",const { initNotSyncedOptions } = await import("./options_init.js");sql.transactional(() => {+ if (schemaExists()) {+ // A previous sync-from-server attempt failed mid-way (schema created, sync never+ // converged) and the user re-submitted the setup form — possibly pointing at a+ // DIFFERENT server. Rebuild from scratch: the partially pulled rows belong to the+ // old seed and would poison the new sync (#10548).+ log.info("Schema exists from a previous unfinished sync setup — wiping it before re-creating.");++ 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.replace(/"/g, '""')}"`);+ }+ }+sql.executeScript(schema);initNotSyncedOptions(false, { syncServerHost, syncProxy, syncMaxBlobContentSize });diff --git a/packages/trilium-core/src/services/sql_init_resetup.spec.ts b/packages/trilium-core/src/services/sql_init_resetup.spec.tsnew file mode 100644index 0000000000..95ea13369d--- /dev/null+++ b/packages/trilium-core/src/services/sql_init_resetup.spec.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";++import * as cls from "./context.js";+import { getSql } from "./sql/index.js";+import sqlInit from "./sql_init.js";++/**+ * Re-running the sync-from-server setup after a FAILED first attempt (#10548).+ *+ * A failed initial sync leaves the database in a half-way state: the schema and the+ * seed options exist, but `initialized` is still false. The user must be able to go+ * back in the setup wizard, correct the server address/credentials and submit again —+ * which calls createDatabaseForSync a second time. That call must rebuild the database+ * from scratch (the partial pull may contain rows from a *different* server) instead of+ * failing on the already-existing schema.+ *+ * Own spec file: this test intentionally destroys and rebuilds the fixture DB, and the+ * per-file fork isolation keeps that away from every other suite.+ */+describe("createDatabaseForSync on a partially set-up database", () => {+ it("rebuilds the schema and replaces the seed options", async () => {+ const sql = getSql();++ // Turn the (initialized) fixture into the failed-setup state: schema + data+ // present, but the initial sync never converged.+ sql.execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");+ expect(sqlInit.schemaExists()).toBe(true);+ expect(sqlInit.isDbInitialized()).toBe(false);+ const staleNoteCount = sql.getValue<number>("SELECT COUNT(*) FROM notes") ?? 0;+ expect(staleNoteCount).toBeGreaterThan(0);++ // cls.init mirrors the route context this runs under in production.+ await cls.init(() => sqlInit.createDatabaseForSync(+ [+ { name: "documentId", value: "resetup-doc-id", isSynced: true, utcDateModified: "2026-07-18 00:00:00.000Z" },+ { name: "documentSecret", value: "resetup-doc-secret", isSynced: true, utcDateModified: "2026-07-18 00:00:00.000Z" }+ ],+ "http://corrected-server:8080"+ ));++ // 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);++ // The new seed and sync options won.+ expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'documentId'")).toBe("resetup-doc-id");+ expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'documentSecret'")).toBe("resetup-doc-secret");+ expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'syncServerHost'")).toBe("http://corrected-server:8080");+ });+});diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.tsindex 337ad43e7a..165329e715 100644--- a/packages/trilium-core/src/services/sync.spec.ts+++ b/packages/trilium-core/src/services/sync.spec.ts@@ -336,6 +336,36 @@ describe("sync service", () => {await expect(runSync()).resolves.toEqual({ success: false, message: "kaboom" });});+ describe("last sync error tracking", () => {+ // The setup wizard's progress screen only polls sync/stats — the sync result itself+ // is returned to whoever *triggered* the sync (often a fire-and-forget). The last+ // error must therefore be queryable so the wizard can leave its progress screen+ // instead of spinning forever (#10548).+ it("records the failure message of the last sync attempt", async () => {+ config.loginThrows = new Error("Request to PUT /api/sync/update failed, error: 401 Logged in session not found");+ await expect(runSync()).resolves.toMatchObject({ success: false });+ expect(syncService.getLastSyncError()).toBe(+ "Request to PUT /api/sync/update failed, error: 401 Logged in session not found"+ );+ });++ it("records connection failures with the user-facing message", async () => {+ config.loginThrows = new Error("connect ECONNREFUSED 127.0.0.1:8080");+ await expect(runSync()).resolves.toMatchObject({ success: false });+ expect(syncService.getLastSyncError()).toBe("No connection to sync server.");+ });++ it("clears the recorded error once a subsequent sync succeeds", async () => {+ config.loginThrows = new Error("kaboom");+ await expect(runSync()).resolves.toMatchObject({ success: false });+ expect(syncService.getLastSyncError()).toBe("kaboom");++ config.loginThrows = undefined;+ await expect(runSync()).resolves.toEqual({ success: true });+ expect(syncService.getLastSyncError()).toBeNull();+ });+ });+describe("login", () => {it("throws when the sync server shares the local instance id", async () => {config.login = { instanceId: getInstanceId(), maxEntityChangeId: 0 };diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex 6e92e4d1ab..0e914604bf 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -28,6 +28,7 @@ let proxyToggle = true;let outstandingPullCount = 0;let totalPullCount: number | null = null;+let lastSyncError: string | null = null;interface CheckResponse {maxEntityChangeId: number;@@ -57,6 +58,10 @@ async function sync() {return { success: false, errorCode: "NOT_CONFIGURED", message: "Sync not configured" };}+ // A new attempt is starting — clear the previous failure so consumers polling+ // getLastSyncError() (the setup wizard) fall back to showing progress.+ lastSyncError = null;+let continueSync = false;do {@@ -107,15 +112,19 @@ async function sync() {log.info("No connection to sync server.");+ lastSyncError = "No connection to sync server.";+return {success: false,- message: "No connection to sync server."+ message: lastSyncError};}log.info(`Sync failed: '${e.message}', stack: ${e.stack}`);ws.syncFailed();+ lastSyncError = e.message;+return {success: false,message: e.message@@ -124,6 +133,17 @@ async function sync() {}}+/**+ * The failure message of the most recent sync attempt, or null when the last attempt+ * succeeded (or none ran yet). The sync result itself only reaches whoever *triggered*+ * the sync — often fire-and-forget (setup, the sync timer) — so the setup wizard's+ * progress screen polls this through `GET /api/sync/stats` to detect that the initial+ * sync has failed instead of spinning forever (#10548).+ */+function getLastSyncError() {+ return lastSyncError;+}+async function login() {if (!(await setupService.hasSyncServerSchemaAndSeed())) {await setupService.sendSeedToSyncServer();@@ -662,6 +682,7 @@ export default {getEntityChangeRecords,getOutstandingPullCount,getTotalPullCount,+ getLastSyncError,getMaxEntityChangeId,startSyncTimer};