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
feat(sync): skip oversized blobs on mobile and show an open-on-server placeholder
Elian Doran47f9f7d5571e
diff --git a/apps/client/src/entities/fblob.ts b/apps/client/src/entities/fblob.tsindex 739027d4d0..514e8093ec 100644--- a/apps/client/src/entities/fblob.ts+++ b/apps/client/src/entities/fblob.ts@@ -4,6 +4,9 @@ export interface FBlobRow {contentLength: number;dateModified: string;utcDateModified: string;+ /** `true` when the blob's content was withheld by the sync server because it exceeded this+ * device's blob size limit (mobile). The content is empty; show an "open on server" placeholder. */+ isStubbed?: boolean;}export default class FBlob {@@ -15,6 +18,9 @@ export default class FBlob {contentLength: number;dateModified: string;utcDateModified: string;+ /** `true` when this blob is a sync stub (content withheld by the server due to the device's blob+ * size limit). See {@link FBlobRow.isStubbed}. */+ isStubbed: boolean;constructor(row: FBlobRow) {this.blobId = row.blobId;@@ -22,6 +28,7 @@ export default class FBlob {this.contentLength = row.contentLength;this.dateModified = row.dateModified;this.utcDateModified = row.utcDateModified;+ this.isStubbed = row.isStubbed ?? false;}/**diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex aa0f294a0f..6b68222d15 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -1,6 +1,6 @@import "./setup.css";-import { LOCALES, NetworkAddressesResponse, SetupSyncFromServerResponse } from "@triliumnext/commons";+import { LOCALES, MOBILE_SYNC_MAX_BLOB_CONTENT_SIZE, NetworkAddressesResponse, SetupSyncFromServerResponse } from "@triliumnext/commons";import clsx from "clsx";import { render } from "preact";import { useEffect, useMemo, useRef, useState } from "preact/hooks";@@ -340,7 +340,11 @@ function SyncFromServer({ setState }: { setState: (state: State) => void }) {const resp = await server.post<SetupSyncFromServerResponse>("setup/sync-from-server", {syncServerHost: syncServerHost.trim().replace(/\/+$/, ""),syncProxy: syncProxy.trim(),- password+ password,+ // On mobile (Capacitor), don't pull blobs above the default limit — they blow the+ // WASM/native heap during sync. The server sends stubs instead; other platforms+ // send 0 (no limit).+ syncMaxBlobContentSize: isMobileApp() ? MOBILE_SYNC_MAX_BLOB_CONTENT_SIZE : 0});if (resp.result === "success") {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c6b70cc03f..cceb32f3e3 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1266,6 +1266,10 @@"search_placeholder": "search for a note by its name","enter_workspace": "Enter workspace {{title}}"},+ "blob_stub": {+ "not_synced": "This note's content is too large to sync to this device. You can open it on the sync server instead.",+ "open_on_server": "Open on server"+ },"file": {"file_preview_not_available": "File preview is not available for this file format.","too_big": "The preview only shows the first {{maxNumChars}} characters of the file for performance reasons. Download the file and open it externally to be able to see the entire content."diff --git a/apps/client/src/widgets/NoteDetail.spec.ts b/apps/client/src/widgets/NoteDetail.spec.tsindex 63e6a9d295..bd55c589c1 100644--- a/apps/client/src/widgets/NoteDetail.spec.ts+++ b/apps/client/src/widgets/NoteDetail.spec.ts@@ -1,12 +1,13 @@import { describe, expect, it, vi } from "vitest";import NoteContext from "../components/note_context";+import type FNote from "../entities/fnote";// NoteDetail pulls in note_tree, which loads jquery.fancytree at import time and needs a `jQuery`// global the test env doesn't provide. The pure function under test never touches the tree, so stub it.vi.mock("./note_tree", () => ({ default: class {} }));-import { isContextInActiveTab } from "./NoteDetail";+import { getExtendedWidgetType, isContextInActiveTab } from "./NoteDetail";/*** Builds a tab as a list of note contexts: the first is the main context (the tab itself),@@ -48,3 +49,41 @@ describe("isContextInActiveTab", () => {expect(isContextInActiveTab(split, undefined)).toBe(false);});});++describe("getExtendedWidgetType blob-stub routing", () => {+ function fakeNote(overrides: Record<string, unknown> = {}): FNote {+ return {+ type: "text",+ isProtected: false,+ isTriliumSqlite: () => false,+ isMarkdown: () => false,+ getBlob: async () => ({ isStubbed: false }),+ ...overrides+ } as unknown as FNote;+ }++ function fakeContext(overrides: Record<string, unknown> = {}): NoteContext {+ return {+ viewScope: {},+ isReadOnly: async () => false,+ ...overrides+ } as unknown as NoteContext;+ }++ it("routes a note whose blob was withheld (stubbed) to the blobStub placeholder", async () => {+ const note = fakeNote({ getBlob: async () => ({ isStubbed: true }) });+ expect(await getExtendedWidgetType(note, fakeContext())).toBe("blobStub");+ });++ it("routes a normal text note to the editable text widget", async () => {+ expect(await getExtendedWidgetType(fakeNote(), fakeContext())).toBe("editableText");+ });++ it("does not fetch the blob for note types that are not blob-backed", async () => {+ const getBlob = vi.fn(async () => ({ isStubbed: true }));+ // A launcher resolves to "doc", which is not blob-backed, so the stub check must be skipped.+ const note = fakeNote({ type: "launcher", getBlob });+ expect(await getExtendedWidgetType(note, fakeContext())).toBe("doc");+ expect(getBlob).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsxindex 9e225f0df8..812d90dd78 100644--- a/apps/client/src/widgets/NoteDetail.tsx+++ b/apps/client/src/widgets/NoteDetail.tsx@@ -409,6 +409,18 @@ export async function getExtendedWidgetType(note: FNote | null | undefined, noteresultingType = type;}+ // A note whose blob was withheld by the sync server (device blob size limit) has empty content;+ // route it to a placeholder rather than a content widget. This also prevents an editor from+ // saving the empty stub back over the real content on the server. Only content-backed types are+ // checked, so blobless notes (docs, launchers, books) don't trigger a needless blob fetch; the+ // fetch itself is froca-cached and coalesced with the render's own blob load.+ if (BLOB_BACKED_TYPES.has(resultingType)) {+ const blob = await note.getBlob();+ if (blob?.isStubbed) {+ resultingType = "blobStub";+ }+ }+if (note.isProtected && !protected_session_holder.isProtectedSessionAvailable()) {resultingType = "protectedSession";}@@ -416,6 +428,13 @@ export async function getExtendedWidgetType(note: FNote | null | undefined, notereturn resultingType;}+// Extended note types that render or edit a note's blob content, and so must fall back to the+// "blobStub" placeholder when that content was not synced to this device.+const BLOB_BACKED_TYPES = new Set<ExtendedNoteType>([+ "editableText", "readOnlyText", "editableCode", "readOnlyCode", "markdown",+ "file", "image", "mermaid", "canvas", "mindMap", "render", "spreadsheet"+]);+export function checkFullHeight(noteContext: NoteContext | undefined, type: ExtendedNoteType | undefined) {if (!noteContext) return false;diff --git a/apps/client/src/widgets/note_types.tsx b/apps/client/src/widgets/note_types.tsxindex 7921f7481c..34c2d7cf9d 100644--- a/apps/client/src/widgets/note_types.tsx+++ b/apps/client/src/widgets/note_types.tsx@@ -12,7 +12,7 @@ import { TypeWidgetProps } from "./type_widgets/type_widget";* A `NoteType` altered by the note detail widget, taking into consideration whether the note is editable or not and adding special note types such as an empty one,* for protected session or attachment information.*/-export type ExtendedNoteType = Exclude<NoteType, "launcher" | "text" | "code" | "llmChat"> | "empty" | "readOnlyCode" | "readOnlyText" | "editableText" | "editableCode" | "attachmentDetail" | "attachmentList" | "protectedSession" | "sqlConsole" | "markdown" | "llmChat";+export type ExtendedNoteType = Exclude<NoteType, "launcher" | "text" | "code" | "llmChat"> | "empty" | "readOnlyCode" | "readOnlyText" | "editableText" | "editableCode" | "attachmentDetail" | "attachmentList" | "protectedSession" | "sqlConsole" | "markdown" | "llmChat" | "blobStub";export type TypeWidget = ((props: TypeWidgetProps) => VNode | JSX.Element | undefined);type NoteTypeView = () => (Promise<{ default: TypeWidget } | TypeWidget> | TypeWidget);@@ -46,6 +46,10 @@ export const TYPE_MAPPINGS: Record<ExtendedNoteType, NoteTypeMapping> = {className: "protected-session-password-component",isFullHeight: true},+ blobStub: {+ view: () => import("./type_widgets/BlobStub"),+ className: "note-detail-blob-stub"+ },book: {view: () => import("./type_widgets/Book"),className: "note-detail-book",diff --git a/apps/client/src/widgets/type_widgets/BlobStub.css b/apps/client/src/widgets/type_widgets/BlobStub.cssnew file mode 100644index 0000000000..1f69b7509c--- /dev/null+++ b/apps/client/src/widgets/type_widgets/BlobStub.css@@ -0,0 +1,9 @@+.note-detail-blob-stub {+ gap: 1em;+ padding: 2em;+ text-align: center;+}++.note-detail-blob-stub button {+ margin-top: 0.5em;+}diff --git a/apps/client/src/widgets/type_widgets/BlobStub.tsx b/apps/client/src/widgets/type_widgets/BlobStub.tsxnew file mode 100644index 0000000000..c1c7c49f72--- /dev/null+++ b/apps/client/src/widgets/type_widgets/BlobStub.tsx@@ -0,0 +1,31 @@+import "./BlobStub.css";++import { t } from "../../services/i18n";+import options from "../../services/options";+import Button from "../react/Button";+import NoItems from "../react/NoItems";+import { TypeWidgetProps } from "./type_widget";++/**+ * Shown in place of the content when a note's blob was not synced to this device because it exceeded+ * the device's blob size limit (`syncMaxBlobContentSize`, set on mobile). The blob is a stub with+ * empty content, so there is nothing to render or edit; offer to open the note on the sync server+ * instead. Rendering this instead of an editor is also a data-safety guard: it prevents the empty+ * stub content from being saved back over the real content on the server.+ */+export default function BlobStub({ note }: TypeWidgetProps) {+ const syncServerHost = options.get("syncServerHost");+ const url = syncServerHost ? `${syncServerHost.replace(/\/+$/, "")}/#root/${note.noteId}` : null;++ return (+ <NoItems className="note-detail-blob-stub" icon="bx bx-cloud-download" text={t("blob_stub.not_synced")}>+ {url && (+ <Button+ kind="primary"+ text={t("blob_stub.open_on_server")}+ onClick={() => window.open(url, "_blank")}+ />+ )}+ </NoItems>+ );+}diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 7ee7e87bf9..4b51fe8d48 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -61,6 +61,7 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActisyncServerTimeoutTimeScale: number;syncProxy: string;syncIncomplete: boolean;+ syncMaxBlobContentSize: number;mainFontFamily: FontFamily;treeFontFamily: FontFamily;detailFontFamily: FontFamily;diff --git a/packages/commons/src/lib/shared_constants.ts b/packages/commons/src/lib/shared_constants.tsindex bab932fdeb..e7600a812c 100644--- a/packages/commons/src/lib/shared_constants.ts+++ b/packages/commons/src/lib/shared_constants.ts@@ -50,3 +50,17 @@ export const SHELL_OPEN_EXTERNAL_PROTOCOLS = ALLOWED_PROTOCOLS.filter(// Shared between the client (<webview partition=...>) and the desktop main// process (session.fromPartition() for permission handlers).export const WEBVIEW_SESSION_PARTITION = "persist:webview";++// Default per-device blob size limit (bytes) applied on mobile (Capacitor). Blobs whose content+// exceeds this are not pulled from the sync server — the client stores an empty-content stub and+// shows an "open on server" placeholder — to bound the peak memory of the WASM/native heap during+// sync. Other platforms default to 0 (no limit). See `syncMaxBlobContentSize`.+export const MOBILE_SYNC_MAX_BLOB_CONTENT_SIZE = 20 * 1024 * 1024;++// blobId of genuinely empty content, i.e. hashedBlobId(""). A blob row that carries empty content+// but a *different* blobId is a sync stub: its real content was withheld by the sync server because+// it exceeded the client's `syncMaxBlobContentSize`. Because `blobId` is content-derived, this+// distinguishes a withheld blob from a legitimately empty one with no extra stored state. The value+// is hard-coded (hashedBlobId needs the platform crypto provider, unavailable at module load in this+// browser-pure package) and guarded by a unit test asserting it equals hashedBlobId("").+export const EMPTY_BLOB_ID = "z4PhNX7vuL3xVChQ1m2A";diff --git a/packages/trilium-core/src/routes/api/setup.spec.ts b/packages/trilium-core/src/routes/api/setup.spec.tsindex 49e5885e05..39a2dee4b0 100644--- a/packages/trilium-core/src/routes/api/setup.spec.ts+++ b/packages/trilium-core/src/routes/api/setup.spec.ts@@ -82,6 +82,29 @@ describe("Setup API (core)", () => {});expect(res.status).toBe(200);expect(res.body.result).toBe("success");- expect(setupSync).toHaveBeenCalledWith("http://host", "", "pw");+ // No blob limit supplied → 0 (unlimited).+ expect(setupSync).toHaveBeenCalledWith("http://host", "", "pw", 0);+ });++ it("threads a positive syncMaxBlobContentSize through to setupSyncFromSyncServer", async () => {+ const setupSync = vi+ .spyOn(setupService, "setupSyncFromSyncServer")+ .mockResolvedValue({ result: "success" });+ const res = await api.post<{ result: string }>("/api/setup/sync-from-server", {+ body: { syncServerHost: "http://host", syncProxy: "", password: "pw", syncMaxBlobContentSize: 20971520 }+ });+ expect(res.status).toBe(200);+ expect(setupSync).toHaveBeenCalledWith("http://host", "", "pw", 20971520);+ });++ it("normalizes an invalid syncMaxBlobContentSize to 0", async () => {+ const setupSync = vi+ .spyOn(setupService, "setupSyncFromSyncServer")+ .mockResolvedValue({ result: "success" });+ const res = await api.post<{ result: string }>("/api/setup/sync-from-server", {+ body: { syncServerHost: "http://host", syncProxy: "", password: "pw", syncMaxBlobContentSize: -5 }+ });+ expect(res.status).toBe(200);+ expect(setupSync).toHaveBeenCalledWith("http://host", "", "pw", 0);});});diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex 443f129b42..0048e8b49a 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -20,9 +20,11 @@ async function setupNewDocument(req: Request) {}function setupSyncFromServer(req: Request): Promise<SetupSyncFromServerResponse> {- const { syncServerHost, syncProxy, password } = req.body;+ const { syncServerHost, syncProxy, password, syncMaxBlobContentSize } = req.body;- return setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password);+ const maxBlobContentSize = Number.isFinite(syncMaxBlobContentSize) && syncMaxBlobContentSize > 0 ? syncMaxBlobContentSize : 0;++ return setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password, maxBlobContentSize);}function saveSyncSeed(req: Request) {diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.tsindex 61a8e85815..159b7ff629 100644--- a/packages/trilium-core/src/routes/api/sync.spec.ts+++ b/packages/trilium-core/src/routes/api/sync.spec.ts@@ -234,6 +234,104 @@ describe("Sync API (core)", () => {});});+ it("stubs blob content larger than maxBlobContentSize while leaving the hash and other rows intact", () => {+ const sql = getSql();+ const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");++ // A large blob (100 bytes) plus a small option change, both from another instance.+ const bigContent = "x".repeat(100);+ sql.execute(+ "INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('bigblob1', ?, '2020-01-01T00:00:00.000Z', '2020-01-01T00:00:00.000Z')",+ [bigContent]+ );+ sql.execute(+ `INSERT INTO entity_changes (id, entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)+ VALUES (?, 'blobs', 'bigblob1', 'blobhash', 0, 'blobchg', 'cmp', 'OTHER', 1, '2020-01-01T00:00:00.000Z')`,+ [maxId + 1]+ );+ const blobChange = sql.getRow<EntityChange>("SELECT * FROM entity_changes WHERE id = ?", [maxId + 1]);++ // Above the limit → content withheld (empty string), but the entity_change (and its hash)+ // is untouched, so the client's content-hash checks still pass.+ const [stubbed] = syncService.getEntityChangeRecords([blobChange], undefined, 50);+ expect(stubbed.entity?.content).toBe("");+ expect(stubbed.entityChange.hash).toBe("blobhash");++ // Below the limit → full (base64-encoded) content is served.+ const [full] = syncService.getEntityChangeRecords([blobChange], undefined, 200);+ expect(typeof full.entity?.content).toBe("string");+ expect((full.entity?.content as string).length).toBeGreaterThan(0);+ expect(full.entity?.content).not.toBe("");++ // No limit at all → also full content (default push/desktop behavior).+ const [unlimited] = syncService.getEntityChangeRecords([blobChange]);+ expect(unlimited.entity?.content).not.toBe("");++ sql.execute("DELETE FROM entity_changes WHERE id = ?", [maxId + 1]);+ sql.execute("DELETE FROM blobs WHERE blobId = 'bigblob1'");+ });++ it("does not stub a blob at or below maxBlobContentSize", () => {+ const sql = getSql();+ const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");++ const smallContent = "y".repeat(10);+ sql.execute(+ "INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('smallblob1', ?, '2020-01-01T00:00:00.000Z', '2020-01-01T00:00:00.000Z')",+ [smallContent]+ );+ sql.execute(+ `INSERT INTO entity_changes (id, entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)+ VALUES (?, 'blobs', 'smallblob1', 'smallhash', 0, 'smallchg', 'cmp', 'OTHER', 1, '2020-01-01T00:00:00.000Z')`,+ [maxId + 1]+ );+ const blobChange = sql.getRow<EntityChange>("SELECT * FROM entity_changes WHERE id = ?", [maxId + 1]);++ // 10 bytes with a 10-byte limit is not "larger than", so it is served in full.+ const [record] = syncService.getEntityChangeRecords([blobChange], undefined, 10);+ expect(record.entity?.content).not.toBe("");++ sql.execute("DELETE FROM entity_changes WHERE id = ?", [maxId + 1]);+ sql.execute("DELETE FROM blobs WHERE blobId = 'smallblob1'");+ });++ it("passes maxBlobContentSize from the query string through to stubbing", async () => {+ const sql = getSql();+ const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");++ const bigContent = "z".repeat(100);+ sql.execute(+ "INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('routeblob1', ?, '2020-01-01T00:00:00.000Z', '2020-01-01T00:00:00.000Z')",+ [bigContent]+ );+ sql.execute(+ `INSERT INTO entity_changes (id, entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)+ VALUES (?, 'blobs', 'routeblob1', 'routehash', 0, 'routechg', 'cmp', 'OTHER', 1, '2020-01-01T00:00:00.000Z')`,+ [maxId + 1]+ );++ type Resp = { entityChanges: { entityChange: EntityChange; entity?: { content?: string } }[] };++ const stubbedRes = await api.get<Resp>("/api/sync/changed", {+ query: { instanceId: "CLIENTX", lastEntityChangeId: String(maxId), maxBlobContentSize: "50" }+ });+ const stubbedRec = stubbedRes.body.entityChanges.find((r) => r.entityChange.entityId === "routeblob1");+ expect(stubbedRec?.entity?.content).toBe("");+ expect(stubbedRec?.entityChange.hash).toBe("routehash");++ // Invalid / non-positive values disable the limit → full content.+ for (const bad of ["0", "-1", "abc"]) {+ const res = await api.get<Resp>("/api/sync/changed", {+ query: { instanceId: "CLIENTX", lastEntityChangeId: String(maxId), maxBlobContentSize: bad }+ });+ const rec = res.body.entityChanges.find((r) => r.entityChange.entityId === "routeblob1");+ expect(rec?.entity?.content).not.toBe("");+ }++ sql.execute("DELETE FROM entity_changes WHERE id = ?", [maxId + 1]);+ sql.execute("DELETE FROM blobs WHERE blobId = 'routeblob1'");+ });+it("getEntityChangeRecords stops accumulating once the response byte cap is reached", () => {const sql = getSql();const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");diff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.tsindex 6acaa38b82..ced73200cd 100644--- a/packages/trilium-core/src/routes/api/sync.ts+++ b/packages/trilium-core/src/routes/api/sync.ts@@ -115,6 +115,12 @@ function forceFullSync() {* schema:* type: string* description: Marker to identify this request in server log+ * - in: query+ * name: maxBlobContentSize+ * required: false+ * schema:+ * type: integer+ * description: If set, blob rows whose content exceeds this many bytes are returned with empty content; the entity_change metadata (including its hash) is unaffected.* responses:* '200':* description: Sync changes, limited to approximately eight megabytes.@@ -149,6 +155,13 @@ function getChanged(req: Request) {let lastEntityChangeId = parseInt(req.query.lastEntityChangeId);const clientInstanceId = req.query.instanceId;+ // Optional per-client limit: blob rows whose content exceeds this many bytes are served with+ // empty content (a stub). Only clients that opt in (currently mobile) send it; the entity_change+ // metadata is unaffected, so content-hash checks still pass. Invalid or non-positive values+ // disable the limit.+ const maxBlobContentSizeRaw = typeof req.query.maxBlobContentSize === "string" ? parseInt(req.query.maxBlobContentSize) : NaN;+ const maxBlobContentSize = Number.isFinite(maxBlobContentSizeRaw) && maxBlobContentSizeRaw > 0 ? maxBlobContentSizeRaw : undefined;+const sql = getSql();const entityChangeRecords: EntityChangeRecord[] = [];let estimatedResponseBytes = 0;@@ -189,7 +202,7 @@ function getChanged(req: Request) {continue;}- const records = syncService.getEntityChangeRecords(foreignEntityChanges, MAX_PULL_RESPONSE_BYTES - estimatedResponseBytes);+ const records = syncService.getEntityChangeRecords(foreignEntityChanges, MAX_PULL_RESPONSE_BYTES - estimatedResponseBytes, maxBlobContentSize);for (const record of records) {estimatedResponseBytes += estimateEntityChangeRecordSize(record);diff --git a/packages/trilium-core/src/services/blob.spec.ts b/packages/trilium-core/src/services/blob.spec.tsindex ace3717d8a..28bc157228 100644--- a/packages/trilium-core/src/services/blob.spec.ts+++ b/packages/trilium-core/src/services/blob.spec.ts@@ -1,3 +1,4 @@+import { EMPTY_BLOB_ID } from "@triliumnext/commons";import { describe, expect, it } from "vitest";import becca from "../becca/becca.js";@@ -8,8 +9,9 @@ import { getContext } from "./context.js";import protectedSessionService from "./protected_session.js";import dataEncryption from "./encryption/data_encryption.js";import notesService from "./notes.js";+import { getSql } from "./sql/index.js";import { decodeUtf8, encodeUtf8 } from "./utils/binary.js";-import { hash } from "./utils/index.js";+import { hash, hashedBlobId } from "./utils/index.js";const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes@@ -170,5 +172,66 @@ describe("blob", () => {expect(pojoContent).toBeNull();expect(contentLength).toBeGreaterThan(0);});++ it("marks a blob as stubbed when content is empty but the blobId is not the empty-content hash", () => {+ const { isStubbed, blobId } = getContext().init(() => {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "blob spec stub note",+ content: "<p>content that was withheld by the sync server</p>",+ type: "text"+ });++ // Simulate a sync stub: the server delivered empty content, but the (content-derived)+ // blobId is still the original non-empty hash.+ getSql().execute("UPDATE blobs SET content = '' WHERE blobId = ?", [note.blobId]);++ const pojo = blob.getBlobPojo("notes", note.noteId);+ return { isStubbed: pojo.isStubbed, blobId: pojo.blobId };+ });++ expect(blobId).not.toBe(EMPTY_BLOB_ID);+ expect(isStubbed).toBe(true);+ });++ it("does not mark a normal (non-empty) blob as stubbed", () => {+ const isStubbed = getContext().init(() => {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "blob spec normal note",+ content: "<p>ordinary content</p>",+ type: "text"+ });+ return blob.getBlobPojo("notes", note.noteId).isStubbed;+ });++ expect(isStubbed).toBe(false);+ });++ it("does not mark a genuinely empty blob as stubbed", () => {+ const { isStubbed, blobId } = getContext().init(() => {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "blob spec empty note",+ content: "<p>temporary</p>",+ type: "text"+ });+ // Empty content hashes to EMPTY_BLOB_ID, so this is a legitimately empty blob, not a stub.+ note.setContent("");++ const pojo = blob.getBlobPojo("notes", note.noteId);+ return { isStubbed: pojo.isStubbed, blobId: pojo.blobId };+ });++ expect(blobId).toBe(EMPTY_BLOB_ID);+ expect(isStubbed).toBe(false);+ });+ });++ describe("EMPTY_BLOB_ID", () => {+ it("equals hashedBlobId of empty content", () => {+ // Guards the hard-coded constant in commons (which cannot call hashedBlobId at module load).+ expect(hashedBlobId("")).toBe(EMPTY_BLOB_ID);+ });});});diff --git a/packages/trilium-core/src/services/blob.ts b/packages/trilium-core/src/services/blob.tsindex 490e27a9fa..2bf98c89fd 100644--- a/packages/trilium-core/src/services/blob.ts+++ b/packages/trilium-core/src/services/blob.ts@@ -1,4 +1,4 @@-import { BlobRow } from "@triliumnext/commons";+import { BlobRow, EMPTY_BLOB_ID } from "@triliumnext/commons";import becca from "../becca/becca.js";import { NotFoundError } from "../errors";import protectedSessionService from "./protected_session.js";@@ -19,13 +19,19 @@ function getBlobPojo(entityName: string, entityId: string, opts?: { preview: booconst pojo = blob.getPojo();+ // A sync stub: the blob carries empty content but its (content-derived) blobId is not the hash of+ // empty content — i.e. its real content was withheld by the sync server because it exceeded this+ // device's `syncMaxBlobContentSize`. Detected before content is decoded/nulled below, off the raw+ // stored length. The client shows an "open on server" placeholder instead of empty content.+ const isStubbed = pojo.contentLength === 0 && pojo.blobId !== EMPTY_BLOB_ID;+if (!entity.hasStringContent()) {pojo.content = null;} else {pojo.content = processContent(pojo.content, !!entity.isProtected, true) as string | Uint8Array;}- return pojo;+ return { ...pojo, isStubbed };}function processContent(content: Uint8Array | string | null, isProtected: boolean, isStringContent: boolean) {diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 04920707f1..e3a4a2a18b 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -19,6 +19,7 @@ export function initDocumentOptions() {interface NotSyncedOpts {syncServerHost?: string;syncProxy?: string;+ syncMaxBlobContentSize?: number;}/**@@ -70,6 +71,9 @@ export async function initNotSyncedOptions(initialized: boolean, opts: NotSyncedoptionService.createOption("syncServerTimeout", "120", false); // 120 seconds (2 minutes)optionService.createOption("syncProxy", opts.syncProxy || "", false);optionService.createOption("syncIncomplete", "false", false);+ // Per-device blob size limit (bytes) for sync pulls; 0 = disabled. Set to a non-zero value only+ // on memory-constrained clients (mobile), so this is not synced across the cluster.+ optionService.createOption("syncMaxBlobContentSize", (opts.syncMaxBlobContentSize ?? 0).toString(), false);}/**@@ -111,6 +115,7 @@ const defaultOptions: DefaultOption[] = [},isSynced: false},+ { name: "syncMaxBlobContentSize", value: "0", isSynced: false },{ name: "revisionSnapshotTimeInterval", value: "600", isSynced: true },{ name: "revisionSnapshotTimeIntervalTimeScale", value: "60", isSynced: true }, // default to Minutes{ name: "revisionSnapshotNumberLimit", value: "-1", isSynced: true },diff --git a/packages/trilium-core/src/services/setup.spec.ts b/packages/trilium-core/src/services/setup.spec.tsindex 7ada44c6ca..220df56331 100644--- a/packages/trilium-core/src/services/setup.spec.ts+++ b/packages/trilium-core/src/services/setup.spec.ts@@ -77,7 +77,20 @@ describe("setup service", () => {const result = await setupService.setupSyncFromSyncServer("http://srv", "proxy", "pw");expect(result).toEqual({ result: "success" });- expect(createSpy).toHaveBeenCalledWith([{ name: "documentId", value: "d" }], "http://srv", "proxy");+ // Default (no mobile limit) forwards 0 as the blob size limit.+ expect(createSpy).toHaveBeenCalledWith([{ name: "documentId", value: "d" }], "http://srv", "proxy", 0);+ });++ it("forwards a blob size limit to createDatabaseForSync", 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" }] });++ await setupService.setupSyncFromSyncServer("http://srv", "proxy", "pw", 20971520);++ expect(createSpy).toHaveBeenCalledWith([{ name: "documentId", value: "d" }], "http://srv", "proxy", 20971520);});it("fails on a sync version mismatch", async () => {diff --git a/packages/trilium-core/src/services/setup.ts b/packages/trilium-core/src/services/setup.tsindex b379e0627c..a6361eb1bd 100644--- a/packages/trilium-core/src/services/setup.ts+++ b/packages/trilium-core/src/services/setup.ts@@ -66,7 +66,7 @@ async function requestToSyncServer<T>(method: string, path: string, body?: strin)) as T;}-async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: string, password: string): Promise<SetupSyncFromServerResponse> {+async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: string, password: string, syncMaxBlobContentSize = 0): Promise<SetupSyncFromServerResponse> {if (sqlInit.isDbInitialized()) {return {result: "failure",@@ -98,7 +98,7 @@ async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: string};}- await sqlInit.createDatabaseForSync(resp.options, syncServerHost, syncProxy);+ await sqlInit.createDatabaseForSync(resp.options, syncServerHost, syncProxy, syncMaxBlobContentSize);triggerSync();diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex 97a6cbdbeb..e0d28f3767 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -224,7 +224,7 @@ async function createInitialDatabase(skipDemoDb?: boolean, locale?: string) {log.info("Database initialization completed, emitted DB_INITIALIZED event");}-async function createDatabaseForSync(options: OptionRow[], syncServerHost = "", syncProxy = "") {+async function createDatabaseForSync(options: OptionRow[], syncServerHost = "", syncProxy = "", syncMaxBlobContentSize = 0) {const log = getLog();const sql = getSql();log.info("Creating database for sync");@@ -239,7 +239,7 @@ async function createDatabaseForSync(options: OptionRow[], syncServerHost = "",sql.transactional(() => {sql.executeScript(schema);- initNotSyncedOptions(false, { syncServerHost, syncProxy });+ initNotSyncedOptions(false, { syncServerHost, syncProxy, syncMaxBlobContentSize });// document options required for sync to kick offfor (const opt of options) {diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.tsindex ff214f75a4..6dac1697d6 100644--- a/packages/trilium-core/src/services/sync.spec.ts+++ b/packages/trilium-core/src/services/sync.spec.ts@@ -126,6 +126,37 @@ describe("sync service", () => {expect(Number(options.getOption("lastSyncedPull"))).toBe(20);});+ it("appends maxBlobContentSize to pull URLs when the option is set", async () => {+ // A single non-empty batch then an empty one so the pull loop terminates.+ config.changed = [+ { entityChanges: [pulledOptionChange()], lastEntityChangeId: 9, outstandingPullCount: 0 },+ { entityChanges: [], lastEntityChangeId: 9, outstandingPullCount: 0 }+ ];+ cls.init(() => options.setOption("syncMaxBlobContentSize", "1048576"));++ await runSync();++ const changedUrls = requestLog.filter((r) => r.url.includes("/api/sync/changed")).map((r) => r.url);+ expect(changedUrls.length).toBeGreaterThan(0);+ expect(changedUrls.every((u) => u.includes("maxBlobContentSize=1048576"))).toBe(true);++ cls.init(() => options.setOption("syncMaxBlobContentSize", "0"));+ });++ it("omits maxBlobContentSize from pull URLs when the option is 0", async () => {+ config.changed = [+ { entityChanges: [pulledOptionChange()], lastEntityChangeId: 9, outstandingPullCount: 0 },+ { entityChanges: [], lastEntityChangeId: 9, outstandingPullCount: 0 }+ ];+ cls.init(() => options.setOption("syncMaxBlobContentSize", "0"));++ await runSync();++ const changedUrls = requestLog.filter((r) => r.url.includes("/api/sync/changed")).map((r) => r.url);+ expect(changedUrls.length).toBeGreaterThan(0);+ expect(changedUrls.some((u) => u.includes("maxBlobContentSize"))).toBe(false);+ });+it("re-runs the content check while the server reports outstanding pulls", async () => {config.check = [{ maxEntityChangeId: 999_999_999, entityHashes: {} }, // lastSyncedPull < max -> loop again@@ -252,6 +283,31 @@ describe("sync service", () => {expect(reorder[0]?.entity).toBeTypeOf("object");});+ it("does not stub oversized blob content when no size limit is passed (push path)", () => {+ // getEntityChangeRecords is shared with the push path, which must never stub: a mobile+ // device that creates a large blob has to push its full content, not an empty stub.+ cls.init(() => {+ getSql().execute(+ "INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('sync_pushpath_blob', ?, ?, ?)",+ ["z".repeat(500), dateUtils.utcNowDateTime(), dateUtils.utcNowDateTime()]+ );+ });+ const records = syncService.getEntityChangeRecords([ec({ entityName: "blobs", entityId: "sync_pushpath_blob" })]);+ expect(records[0]?.entity?.content).not.toBe("");+ });++ it("stubs oversized blob content when a size limit is passed", () => {+ cls.init(() => {+ getSql().execute(+ "INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES ('sync_stub_blob', ?, ?, ?)",+ ["z".repeat(500), dateUtils.utcNowDateTime(), dateUtils.utcNowDateTime()]+ );+ });+ const [record] = syncService.getEntityChangeRecords([ec({ entityName: "blobs", entityId: "sync_stub_blob" })], undefined, 100);+ expect(record?.entity?.content).toBe("");+ expect(record?.entityChange.hash).toBe("remote"); // the ec hash is left untouched+ });+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/);diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex 1fb47a39fc..b56b4470e7 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -164,6 +164,7 @@ async function doLogin(): Promise<SyncContext> {async function pullChanges(syncContext: SyncContext) {const log = getLog();const maxBatchBytes = getMaxPullBatchBytes();+ const maxBlobContentSize = getMaxBlobContentSize();while (true) {// Fetch phase: pull consecutive chunks (each needs its own HTTP round-trip) until we've@@ -180,7 +181,8 @@ async function pullChanges(syncContext: SyncContext) {do {const logMarkerId = randomString(10); // to easily pair sync events between client and server logs- const changesUri = `/api/sync/changed?instanceId=${getInstanceId()}&lastEntityChangeId=${cursor}&logMarkerId=${logMarkerId}`;+ const changesUri = `/api/sync/changed?instanceId=${getInstanceId()}&lastEntityChangeId=${cursor}&logMarkerId=${logMarkerId}`+ + (maxBlobContentSize ? `&maxBlobContentSize=${maxBlobContentSize}` : "");const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);if (!resp) {@@ -425,7 +427,7 @@ async function syncRequest<T extends {}>(syncContext: SyncContext, method: strinreturn response;}-function getEntityChangeRow(entityChange: EntityChange) {+function getEntityChangeRow(entityChange: EntityChange, maxBlobContentSize?: number) {const { entityName, entityId } = entityChange;if (entityName === "note_reordering") {@@ -449,6 +451,16 @@ function getEntityChangeRow(entityChange: EntityChange) {entityRow.content = binary_utils.encodeUtf8(entityRow.content);}+ // A client that opted into a blob size limit (e.g. mobile, to bound peak memory) receives a+ // stub for oversized blobs: the entity_change row — and crucially its hash — is sent+ // unchanged, so the client's content-hash checks still pass, while the entity row carries an+ // empty string (never null, which the consistency checker would "repair" and push back). The+ // client stores an empty-content blob and shows an "open on server" placeholder. Measured on+ // the raw (pre-base64) content, so the threshold matches the user-facing byte size.+ if (maxBlobContentSize && entityRow.content && typeof entityRow.content !== "string" && entityRow.content.byteLength > maxBlobContentSize) {+ entityRow.content = "";+ }+if (entityRow.content) {entityRow.content = binary_utils.encodeBase64(entityRow.content);}@@ -470,7 +482,7 @@ function getEntityChangeRow(entityChange: EntityChange) {*/export const MAX_PULL_RESPONSE_BYTES = 8 * 1024 * 1024;-function getEntityChangeRecords(entityChanges: EntityChange[], maxResponseBytes = MAX_PULL_RESPONSE_BYTES) {+function getEntityChangeRecords(entityChanges: EntityChange[], maxResponseBytes = MAX_PULL_RESPONSE_BYTES, maxBlobContentSize?: number) {const records: EntityChangeRecord[] = [];let length = 0;@@ -481,7 +493,7 @@ function getEntityChangeRecords(entityChanges: EntityChange[], maxResponseBytescontinue;}- const entity = getEntityChangeRow(entityChange);+ const entity = getEntityChangeRow(entityChange, maxBlobContentSize);if (!entity) {continue;}@@ -518,6 +530,18 @@ function getLastSyncedPull() {return parseInt(optionService.getOption("lastSyncedPull"));}+/**+ * Per-device limit (in bytes) above which blob content is not pulled from the sync server; the+ * server sends an empty-content stub instead. `0` (or an unset/invalid option) disables the limit,+ * which is the default for every platform except mobile. Read with `getOptionOrNull` so databases+ * created before this option existed do not throw.+ */+function getMaxBlobContentSize(): number {+ const value = parseInt(optionService.getOptionOrNull("syncMaxBlobContentSize") ?? "0");++ return Number.isFinite(value) && value > 0 ? value : 0;+}+function setLastSyncedPull(entityChangeId: number) {const lastSyncedPullOption = becca.getOption("lastSyncedPull");