Skip to content

Build your personal knowledge base with Trilium Notes

fix(mobile/ios): make initial sync survive on memory-constrained WebView

AndreeaCorlaci960b1e66b83a
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsx
index e24353e50e..69b09b33cc 100644
--- a/apps/client/src/setup.tsx
+++ b/apps/client/src/setup.tsx
@@ -52,7 +52,12 @@ function renderState(state: State, setState: (state: State) => void) {
}
function App() {
- const [state, setState] = useState<State>("selectLanguage");
+ // If the bootstrap signals that a previous setup left a partial sync, jump
+ // straight to the sync-in-progress screen. The worker auto-restarts sync,
+ // and we don't want the user re-entering host/password or seeing the
+ // language picker again — they're effectively resuming.
+ const initialState: State = glob.setupResuming ? "syncFromServerInProgress" : "selectLanguage";
+ const [state, setState] = useState<State>(initialState);
const [prevState, setPrevState] = useState<State | null>(null);
const [transitioning, setTransitioning] = useState(false);
const prevStateRef = useRef<State>(state);
diff --git a/apps/standalone/src/lightweight/bridged_request_provider.ts b/apps/standalone/src/lightweight/bridged_request_provider.ts
index 98447dba57..aee83d66d4 100644
--- a/apps/standalone/src/lightweight/bridged_request_provider.ts
+++ b/apps/standalone/src/lightweight/bridged_request_provider.ts
@@ -100,16 +100,27 @@ export default class BridgedRequestProvider implements RequestProvider {
}
if ([200, 201, 204].includes(msg.status)) {
+ // Fast path: main thread sent the already-parsed JSON object via
+ // structured clone. Use it directly — no second JSON.parse, no
+ // intermediate string allocation. Critical for large blob batches
+ // on memory-constrained clients (iOS Capacitor WebView worker).
+ if (msg.data !== undefined) {
+ return msg.data;
+ }
const text = msg.body || "";
return text.trim() ? JSON.parse(text) : null;
}
let errorMessage: string;
- try {
- const json = JSON.parse(msg.body || "");
- errorMessage = json?.message || "";
- } catch {
- errorMessage = (msg.body || "").substring(0, 100);
+ if (msg.data && typeof msg.data === "object") {
+ errorMessage = (msg.data as { message?: string }).message ?? "";
+ } else {
+ try {
+ const json = JSON.parse(msg.body || "");
+ errorMessage = json?.message || "";
+ } catch {
+ errorMessage = (msg.body || "").substring(0, 100);
+ }
}
throw new Error(`${msg.status} ${opts.method} ${opts.url}: ${errorMessage}`);
}
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index 98e18e56c8..4d0647686a 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -4,7 +4,7 @@
*/
import { BootstrapDefinition } from '@triliumnext/commons';
-import { entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, routes, sql_init } from '@triliumnext/core';
+import { entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, options, routes, sql_init } from '@triliumnext/core';
import packageJson from '../../package.json' with { type: 'json' };
import { type BrowserRequest, BrowserRouter } from './browser_router';
@@ -315,10 +315,19 @@ function bootstrapRoute(): BootstrapDefinition {
};
if (!isDbInitialized) {
+ // Resume case: schema is already present from a previous setup attempt
+ // that was interrupted before sync completed. Tell the client to skip
+ // the language/sync-from-server forms and go straight to the
+ // sync-in-progress UI — sync itself is auto-restarted by the worker.
+ const setupResuming = sql_init.schemaExists()
+ && parseInt(options.getOptionOrNull("lastSyncedPull") ?? "0") > 0
+ && !!options.getOptionOrNull("syncServerHost");
+
return {
...commonItems,
baseApiUrl: "../api/",
isProtectedSessionAvailable: false,
+ setupResuming,
};
}
diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.ts
index 576a5e2f94..1c039b1a68 100644
--- a/apps/standalone/src/local-bridge.ts
+++ b/apps/standalone/src/local-bridge.ts
@@ -50,7 +50,17 @@ export type NativeHttpHandler = (request: {
}) => Promise<{
status: number;
headers: Record<string, string>;
- body: string;
+ // Exactly one of these will be set:
+ // - `data` carries an already-parsed JSON response straight through the
+ // structured-clone postMessage. The worker uses it as-is and skips
+ // JSON.parse, avoiding the ~2× memory blowup that killed large blobs
+ // (parsed object + an intermediate ~60MB string was OOM-ing the iOS
+ // worker). The handler must NOT JSON.stringify the response itself.
+ // - `body` is the raw string body — used for non-JSON responses (e.g.
+ // base64 binary returned for `responseType: "arraybuffer"`) and for
+ // error bodies the worker needs to inspect.
+ data?: unknown;
+ body?: string;
}>;
let nativeHttpHandler: NativeHttpHandler | null = null;
diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.ts
index 57d96ae0a9..e8a752ddf5 100644
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@ -308,6 +308,25 @@ async function initialize(): Promise<void> {
}
} else {
logService.info("[Worker] Database not initialized, skipping becca load (will be loaded during DB initialization)");
+
+ // Auto-resume an interrupted initial sync. If the schema is
+ // present and the user already configured sync in a previous
+ // session that didn't finish, restart sync from `lastSyncedPull`
+ // so the user stays on the sync-in-progress screen without
+ // re-entering credentials. The DB will only be marked initialized
+ // once `sync()` returns success (handled inside `triggerSync`).
+ if (coreModule.sql_init.schemaExists()) {
+ const lastSyncedPull = parseInt(
+ coreModule.options.getOptionOrNull("lastSyncedPull") ?? "0"
+ );
+ const syncServerHost = coreModule.options.getOptionOrNull("syncServerHost") ?? "";
+ if (lastSyncedPull > 0 && syncServerHost) {
+ logService.info(
+ `[Worker] Resuming interrupted sync: lastSyncedPull=${lastSyncedPull}, host=${syncServerHost}`
+ );
+ coreModule.setup.triggerSync();
+ }
+ }
}
coreModule.scheduler.startScheduler();
diff --git a/apps/standalone/src/services/capacitor_http_handler.ts b/apps/standalone/src/services/capacitor_http_handler.ts
index 8ed7befd40..2cd464a459 100644
--- a/apps/standalone/src/services/capacitor_http_handler.ts
+++ b/apps/standalone/src/services/capacitor_http_handler.ts
@@ -31,6 +31,13 @@ function getCapacitorHttp() {
*
* This bypasses the WebView's fetch — no CORS preflight, no SameSite cookie
* restrictions, and plain HTTP targets work from an HTTPS WebView origin.
+ *
+ * Memory-critical: for JSON responses we pass `response.data` (already parsed
+ * by Capacitor) directly through postMessage instead of re-stringifying. The
+ * worker receives a structured-clone copy and skips its own JSON.parse. This
+ * avoids holding two ~60 MB strings (one on each side of the bridge) plus the
+ * parsed object simultaneously, which was OOM-killing the iOS Web Worker on
+ * large blob sync batches.
*/
export const capacitorHttpHandler: NativeHttpHandler = async (request) => {
const response = await getCapacitorHttp().request({
@@ -47,15 +54,19 @@ export const capacitorHttpHandler: NativeHttpHandler = async (request) => {
headers[key.toLowerCase()] = value;
}
- let body: string;
+ // Binary responses come back from Capacitor as a base64 string — pass it
+ // through as `body` so the worker's atob+Uint8Array path still works.
if (request.responseType === "arraybuffer") {
- // Capacitor returns binary data as a base64 string — pass it through directly
- body = String(response.data);
- } else {
- body = typeof response.data === "string"
- ? response.data
- : JSON.stringify(response.data);
+ const body = typeof response.data === "string" ? response.data : String(response.data);
+ return { status: response.status, headers, body };
+ }
+
+ // Server-sent plain strings (rare for JSON APIs, but valid) — pass through.
+ if (typeof response.data === "string") {
+ return { status: response.status, headers, body: response.data };
}
- return { status: response.status, headers, body };
+ // Common case: JSON. Hand the parsed object to the worker via structured
+ // clone. No intermediate string allocation on either side.
+ return { status: response.status, headers, data: response.data };
};
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 7d1be2f4af..0234a8f01b 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -392,6 +392,14 @@ export type BootstrapDefinition = {
isRtl: boolean;
TRILIUM_SAFE_MODE: boolean;
componentId?: string;
+ /**
+ * Set when the DB has a partial sync (schema exists, sync server is
+ * configured, lastSyncedPull > 0, but `options.initialized` is not "true").
+ * The standalone client uses this to skip the language/sync-from-server
+ * forms and jump straight to the sync-in-progress UI, since the user
+ * already entered those values in a previous (interrupted) session.
+ */
+ setupResuming?: boolean;
};
/**
diff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.ts
index 9250b251c4..b1d11c5606 100644
--- a/packages/trilium-core/src/routes/api/sync.ts
+++ b/packages/trilium-core/src/routes/api/sync.ts
@@ -174,11 +174,17 @@ function getChanged(req: Request) {
}
} while (filteredEntityChanges.length === 0);
- const entityChangeRecords = syncService.getEntityChangeRecords(filteredEntityChanges);
+ const { records: entityChangeRecords, lastSeenEntityChangeId } =
+ syncService.getEntityChangeRecords(filteredEntityChanges);
+
+ // Advance past entities the loop processed even when the batch yields no
+ // records (defensive — covers the case where every entity in the batch was
+ // a no-op or was otherwise skipped by getEntityChangeRecords).
+ if (lastSeenEntityChangeId != null) {
+ lastEntityChangeId = lastSeenEntityChangeId;
+ }
if (entityChangeRecords.length > 0) {
- lastEntityChangeId = entityChangeRecords[entityChangeRecords.length - 1].entityChange.id;
-
getLog().info(`Returning ${entityChangeRecords.length} entity changes in ${Date.now() - startTime}ms`);
}
diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.ts
index e7ec335159..3ea6b7b45f 100644
--- a/packages/trilium-core/src/services/sync.ts
+++ b/packages/trilium-core/src/services/sync.ts
@@ -203,14 +203,27 @@ async function pullChanges(syncContext: SyncContext) {
});
if (entityChanges.length === 0) {
+ // Server may have advanced lastEntityChangeId past entities that
+ // were skipped (either by server-side maxEntitySize or stripped by
+ // a client-side filter before reaching here). If server reports
+ // more outstanding AND we actually advanced, keep pulling instead
+ // of bouncing back to the outer sync() loop, which would re-login,
+ // re-push, etc., for every single skipped batch.
+ const advanced = lastSyncedPull !== lastEntityChangeId;
+ if (outstandingPullCount > 0 && advanced) {
+ continue;
+ }
break;
} else {
try {
- // https://github.com/zadam/trilium/issues/4310
- const sizeInKb = Math.round(JSON.stringify(resp).length / 1024);
-
+ // Don't `JSON.stringify(resp)` here — for memory-constrained clients
+ // (iOS WebView worker) a single ~60MB blob response would force a
+ // second ~60MB string allocation immediately after the parsed object
+ // is still in scope, peaking the worker heap and OOM-killing it. Log
+ // the entity count instead; we already know the wire size from the
+ // raw body length when the response was received.
log.info(
- `Sync ${logMarkerId}: Pulled ${entityChanges.length} changes in ${sizeInKb} KB, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`
+ `Sync ${logMarkerId}: Pulled ${entityChanges.length} changes, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`
);
} catch (e: any) {
log.error(`Error occurred ${e.message} ${e.stack}`);
@@ -255,7 +268,7 @@ async function pushChanges(syncContext: SyncContext) {
continue;
}
- const entityChangesRecords = getEntityChangeRecords(filteredEntityChanges);
+ const { records: entityChangesRecords } = getEntityChangeRecords(filteredEntityChanges);
const startDate = new Date();
const logMarkerId = randomString(10); // to easily pair sync events between client and server logs
@@ -393,14 +406,20 @@ function getEntityChangeRow(entityChange: EntityChange) {
}
-function getEntityChangeRecords(entityChanges: EntityChange[]) {
+function getEntityChangeRecords(
+ entityChanges: EntityChange[]
+): { records: EntityChangeRecord[]; lastSeenEntityChangeId: number | null } {
const records: EntityChangeRecord[] = [];
let length = 0;
+ let lastSeenEntityChangeId: number | null = null;
for (const entityChange of entityChanges) {
+ if (entityChange.id != null) {
+ lastSeenEntityChangeId = entityChange.id;
+ }
+
if (entityChange.isErased) {
records.push({ entityChange });
-
continue;
}
@@ -410,9 +429,7 @@ function getEntityChangeRecords(entityChanges: EntityChange[]) {
}
const record: EntityChangeRecord = { entityChange, entity };
-
records.push(record);
-
length += JSON.stringify(record).length;
if (length > 1_000_000) {
@@ -421,7 +438,7 @@ function getEntityChangeRecords(entityChanges: EntityChange[]) {
}
}
- return records;
+ return { records, lastSeenEntityChangeId };
}
function getLastSyncedPull() {